Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...