点击链接更改网址,但不更改页面上的内容/数据

rma*_*002 7 vue.js vue-router

故事:

我在产品页面#/product/7和同一页面上我还有4个产品与正在查看的产品相似.所有这些产品都有链接到他们的页面:

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

问题:

当我点击任何产品链接时,网址会发生变化但内容保持不变.所以,如果我打开#/product/7并点击#/product/8该网址只会改变.如果我从/product/:id页面导航并单击某个产品,它会将我带到正确的页面并显示正确的内容.

在此输入图像描述

正如您在屏幕截图中看到的那样,当前产品ID为15,但内容是来自id 7的内容,如底部的url所示,而我正在购物车中的Sleek Silk Shirt产品上方悬停.任何想法如何解决这一问题?

Sau*_*abh 11

更改路径时,必须更新products变量的数据,因为vue优化页面重新加载,如果您在同一路径上,则不会重新加载.

您可以调整方法:Fetching Before Navigation 在vue-router docs中描述:

通过这种方法,我们在实际导航到新路线之前获取数据.我们可以在传入组件中的beforeRouteEnter防护中执行数据获取,并且只在获取完成时调用next:

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
        }
      })
    }
  }
}
Run Code Online (Sandbox Code Playgroud)