I currently used
asyncData
for getting api data , but it can only used in pages ( not in ponents) .- But method can used in page and ponent .
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
}
}
I currently used
asyncData
for getting api data , but it can only used in pages ( not in ponents) .- But method can used in page and ponent .
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
}
}
Share
Improve this question
asked Dec 28, 2017 at 10:13
Jack jdeoelJack jdeoel
4,5846 gold badges28 silver badges56 bronze badges
2 Answers
Reset to default 2There is a very big difference:
asyncData
is a method which gets automatically called before the ponent gets initialized and therefore before the ponent 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 ponent gets rendered with the fetched data. Nuxt will wait until the data got fetched before initializing and then rendering the ponent. Otherwise it would be rendered empty.
Methods are first available when the ponent is initialized.
You'll find more about asyncData here in the docs and there it's good described.
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 ining 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