单击链接会更改 url 但不会更改页面上的内容/数据 [英] Click on link changes the url but not the content/data on page

查看:26
本文介绍了单击链接会更改 url 但不会更改页面上的内容/数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

故事:

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

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').

问题:

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

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.

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

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?

推荐答案

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

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.

您可以调整方法:Fetching Before Navigation 在 vue-router 文档:

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

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

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

这篇关于单击链接会更改 url 但不会更改页面上的内容/数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆