'asyncData or fetch method with Parameters in NuxtJs

I'm working on a nuxtjs project, using asyncData and fetch methods but I need to use parameterize url for get requests and the parameters are present in the data property of vue. How will I use it.

....
data(){
 return {
  param1: "455",
  param2: "xyz",
  products: []
}
},
asyncData(){
    return axio.get(`/api/products?type=${param1}&cat{param2}`).then(response => {
    this products = response.data
 })
}

The approach I used here for parameterize url is correct? Please also discuss for fetch methods as well



Solution 1:[1]

You can't. asyncData hook runs before creating the component, so it doesn't have access to the component instance (because it doesn't exists yet).

asyncData could have access to global properties throught the Nuxt context, such as:

  • route parameters
  • vuex store
  • injected properties with plugins

You could use the fetch hook instead, which does have access to this (the component instance). The difference is that it won't block the page render on client navigation, so you have to handle the loading state with $fetchState.pending.

fetch () {
  return axio.get(`/api/products?type=${this.param1}&cat{this.param2}`).then(response => {
    this products = response.data
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kapcash