Component works only once using router-link - Laravel vue

Viewed 263

I am working on a project that uses Laravel Vue SPA, and I got a problem accessing the data of the single product, it's only working when I click once, but when I select again with other product, I can't get the product data, but the URL is correct it's changes the ID but can't access the data.

It is working when I click another link like Services then select product, it can display the product data.

Here is my HTML

<ul >
    <li v-for="product in products">
        <router-link :to="{ name: 'edit-product', params: { id: product.id } }">
            {{ product.title }}
        </router-link>
    </li>
</ul>

My Vue Routes

const EditProduct = require('./components/EditProduct').default;
{ 
    path: '/edit/product/:id', 
    component: EditProduct, 
    name: 'edit-product'
}

my EditProduct component

<template>
    <div>
        <h1>this.$route.params.id</h1>
    </div>
</template>

Cheers

2 Answers

try to define a computed property inside your EditProduct component for get product id

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

and use productId inside your <h1> tag

<template>
    <div>
        <h1>{{ productId }}</h1>
    </div>
</template>

update

solution :

add this watcher to your EditProduct component for reacting with params change

watch: {
  $route(to) {
    console.log(to.params.id)
    // you can call your method here and pass product id to them for example:  this.getProductDetails(to.params.id)
  },
beforeRouteEnter (to, from, next) {
  next(vm => { 
     //also call your method here =>  vm.getProductDetails(to.params.id)
  });
},

you can read more about params changes here: Reacting to Params Changes

Look at this answer. You have to watch the productId and execute your logic again.

Possible solution

Related