Click on link changes the url but not the content/data on page

7.1k Views Asked by At

the story:

I am on product page #/product/7 and on the same page I have 4 more products that are similar to the one that is being viewed. All these products have links to their pages:

router-link(:to="{ name: 'product', params: { id: product.id }}" v-text='product.title').

the problem:

When I click on any of the product links, the url changes but the content remains the same. So, if I am on #/product/7 and click on #/product/8 the url only will change. If I navigate from /product/:id page and click on a product it takes me to the right page with proper content.

enter image description here

As you can see on screenshot, current product id is 15, but the content is the one from the id 7, as shown in url at the bottom while I was hovering over the Sleek Silk Shirt product in cart. Any ideas how to fix this?

2

There are 2 best solutions below

3
On BEST ANSWER

You have to update the data of products variable when you change the route as vue optimises page reloads and does not reload in your case if you are on same route.

You can adapt the approach: Fetching Before Navigation described in vue-router docs:

With this approach we fetch the data before actually navigating to the new route. We can perform the data fetching in the beforeRouteEnter guard in the incoming component, and only call next when the fetch is complete:

export default {
  data () {
    return {
      product: {},
      error: null
    }
  },
  beforeRouteEnter (to, from, next) {
    getProduct(to.params.id, (err, product) => {
      if (err) {
        // display some global error message
        next(false)
      } else {
        next(vm => {
          vm.product = product
        })
      }
    })
  },
  // when route changes and this component is already rendered,
  // the logic will be slightly different.
  watch: {
    $route () {
      this.product = {}
      getProduct(this.$route.params.id, (err, product) => {
        if (err) {
          this.error = err.toString()
        } else {
          this.product = product
        }
      })
    }
  }
}
0
On

I couldnt really internalise the above answer with 'getProduct', so to be put simply.

I am using a Store and I needed to watch the $route and when it changes I called my store to dispatch the api call.

watch: {
    $route () {
      this.$store.dispatch('fetchStudyStandards', 
      this.$route.params.standardID);
    }
}

So basically watch the route and if it changes, re do your api call.