首页 > 解决方案 > Nuxt 在 hook fetch/asyncData 中访问组件的方法或数据

问题描述

在我的组件上,我有以下脚本:

<script>
 export default {
  data(){
   return {
    posts: [],
   }
  }
  methods: {
   async get_post(){
    return await this.$axios('post')
   }
  }
 }
</script>

我想在不直接使用 axios 的情况下从 fetch 或 asyncData 挂钩访问我的数据和方法,在 fetch 上尝试了“this”,但只能访问数据而不是方法,在 asyncData 上我什至无法访问这两者。

标签: vue.jsfetchnuxt.jsasyncdata

解决方案


根据文档:数据获取

asyncData

您只能访问上下文asyncData()(另外,请记住asyncData()仅在页面组件中可用)

所以你可以像这样编码

<script>
 export default {
  asyncData({ $axios }){
    return $axios.post('/users')
  }
 }
</script>

fetch

但您可以访问其中的数据和方法fetch()

export default {
  data: () => ({
    posts: []
  }),
  async fetch() {
    this.posts = await this.$http.$get('https://api.nuxtjs.dev/posts')
  },
  fetchOnServer: false,
  // multiple components can return the same `fetchKey` and Nuxt will track them both separately
  fetchKey: 'site-sidebar',
  // alternatively, for more control, a function can be passed with access to the component instance
  // It will be called in `created` and must not depend on fetched data
  fetchKey(getCounter) {
    // getCounter is a method that can be called to get the next number in a sequence
    // as part of generating a unique fetchKey.
    return this.someOtherData + getCounter('sidebar')
  }
}

推荐阅读