无法与nuxt异步显示数据

Impossible to display data asynchronously with nuxt

我正在使用静态 vue 网站使用 wordpress rest 获取数据 api。

我正在尝试在 vue 页面的 API 上显示我获取的数据:

<template>
    <div>
        <h1>
          {{ title }}
        </h1>
        <template>
          {{ content }}
        </template>
        <p><nuxt-link to="/">Back to home page</nuxt-link></p>
    </div>
</template>

<script>
import axios from 'axios'

export default {
  validate({ params }) {
    return isNaN(+params.slug)
  },
  asyncData({ params, error }) {
    let slug = params.slug;
    // We can return a Promise instead of calling the callback
    return axios.get('https://dev.lesdeuxvagues.com/api/wp-json/wp/v2/posts/?slug='+slug)
      .then((res) => {
        return { data: res.data }
      })
  },
}

</script>

我也试过这种方式:

<template>
    <div>
        <h1>
          {{ title }}
        </h1>
        <template>
          {{ content }}
        </template>
        <p><nuxt-link to="/">Back to home page</nuxt-link></p>
    </div>
</template>

<script>
import axios from 'axios'
export default {
  validate({ params }) {
    return isNaN(+params.slug)
  },
  async asyncData({ params, error }) {
    try {
      let slug = params.slug;
      const { data } = await axios.get(`https://dev.lesdeuxvagues.com/api/wp-json/wp/v2/posts/?slug=`+slug)
      return data
    } catch (e) {
      error({ message: 'Article not found', statusCode: 404 })
    }
  }
}
</script>

但这两种解决方案都不起作用...

我认为问题出在异步函数上,但我不明白为什么..

在此先感谢您的帮助

这就是您可能想要尝试的方法。当然,您可以根据自己的方便自定义 API。

<template>
    <p>
        {{data}}
    </p>
</template>

<script>
import axios from 'axios'

export default {

    asyncData(context) {
        // We can return a Promise instead of calling the callback
        return axios.get('https://dev.lesdeuxvagues.com/api/wp-json/wp/v2/posts/')
            .then((res) => {
                return {
                    data: res.data[0]
                }
            })
    },
}

</script>