Nuxt access component's method or data in hook fetch/asyncData

1k Views Asked by At

On my component i have follow script:

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

I want to access my data and my methods from fetch or asyncData hook without using the axios directly there, tried "this" on fetch but only data is accessible but not the methods, on asyncData i can't even access the two.

1

There are 1 best solutions below

1
DengSihan On

according to the doc: Data Fetching

asyncData

you can only access the context in asyncData()(also, please remember the asyncData() is only avaiables in page components)

so you can code like

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

fetch

but you can access the data and methods in 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')
  }
}