aspile
aspile

Reputation: 593

How to pass props parameter with axios in Vuejs?

I am passing a property in another component via props:

props: ['product']

This Product has some properties like: id, name etc.

Now, I want to get the category of this product with id via axios.

Is it possible? How? My try:

mounted () {
   axios
   .get('/categoryofaproduct/', {
       params: {
          id: this.product.id
       }
   })
   .then(response => {
       console.log(response)
  })
}

Upvotes: 1

Views: 1238

Answers (2)

Floyd Watson
Floyd Watson

Reputation: 408

I would recommend to use back ticks to make it a string literal and interpolation to insert the values in. This just makes it more readable when you have multiple parameters in a URL

mounted () {
   axios
   .get(`/categoryofaproduct/${this.product.id}`
                 
)
   .then(response => {
       console.log(response)
  })
}

Then accept that parameter on your route

 {
      // create route with id as a parameter
      path: "/categoryofaproduct/:id",
      name: "category-of-a-product",
      component: () => import("./views/categoryofaproduct.vue"),
    },

To get access to that param create a computed field that returns it

 computed: {
    paramsId() {
      return this.$route.params.id
    },
}

Upvotes: 0

Mr. Perfectionist
Mr. Perfectionist

Reputation: 2746

I think Props properties will not be accessable directly like this.

data() {
  return {
     id: null,
     categoryName: null
  }
}

In mounted you can copy the id like this and then it will work.

mounted () {
  this.id = this.product.id
  axios.get('/categoryofaproduct/'+this.id)
    .then(response => {
      this.categoryName = response.data
    })
}

Upvotes: 1

Related Questions