Click the link to change the URL, but not the content / data on the page.

story:

I am on the 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').

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/7and clicking #/product/8, then the URL will change. If I go from the page /product/:idand click on the product, it will return me to the desired page with the appropriate content.

enter image description here

As you can see in the screenshot, the current product identifier is 15, but the content is one of the identifier 7, as shown in the url below, while I was hovering over the Sleek Silk Shirt product in the basket. Any ideas how to fix this?

+3
source share
1 answer

When changing the route, you need to update the data of the product variable, since vue optimizes page reloading and does not reload in your case if you are on the same route.

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

. beforeRouteEnter , :

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
        }
      })
    }
  }
}
+6

Source: https://habr.com/ru/post/1665453/


All Articles