4

I currently used

  • asyncData for getting api data , but it can only used in pages ( not in components) .
  • But method can used in page and component .

These two method work the same ways and , so I am thinking to use methods for getting api data . So I wonder is there any significant between asyncData and method ?

export default {
  async asyncData ({ req }) {
    let { data } = await axios.get(process.env.API_SERVER + `/v1/projects`)
    return { items: data }
  },
  data () {
    return {
      items: null
    }
  },
  methods: {
    async getItems () {
       let { data } = await axios.get(process.env.API_SERVER + `/v1/projects`)
       this.items = data
    }
  }
Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52

2 Answers2

2

There is a very big difference:

asyncData is a method which gets automatically called before the component gets initialized and therefore before the component data gets set.

Therefore you won't have access to this like in your methods.

asyncData is important for server side rendering where you want to fetch first your data before your component gets rendered with the fetched data. Nuxt will wait until the data got fetched before initializing and then rendering the component. Otherwise it would be rendered empty.

Methods are first available when the component is initialized.

You'll find more about asyncData here in the docs and there it's good described.

Soleno
  • 1,949
  • 1
  • 11
  • 8
1

its like automatic promise

once you (ajax) request something then you get promise so you add then handler so when you get data your then code will be executed.

so ajax request will take some time so we are making that flow as async means continue the flow but when data received i need to execute some code which i have provided in then function

same goes with asyncData(its just wrapper for data with async capabilities) and async method what ever code you write inside will await for the given operation then when that operation is finished method will be executed.

its just like alert('hello') which await user for to click ok then continue the flow.

as well in server-side rendering it work same it will stop execution flow for a while for incoming data then again resumes it.

it more on depth with this js generators answer (if you are more interested): Difference between async/await and ES6 yield with generators

Hardik Satasiya
  • 9,547
  • 3
  • 22
  • 40