组件仅使用路由器链接工作一次 - Laravel vue solution :

问题描述

我正在做一个使用Laravel Vue SPA的项目,访问单个产品的数据时出现问题,只有点击一次才有效,但是当我再次选择其他产品时,我无法获取产品数据,但 URL 正确 更改 ID 但无法访问数据。

当我点击另一个链接(如 Services)然后选择产品时,它可以工作,它可以显示产品数据。

这是我的 HTML

<ul >
    <li v-for="product in products">
        <router-link :to="{ name: 'edit-product',params: { id: product.id } }">
            {{ product.title }}
        </router-link>
    </li>
</ul>

我的 Vue 路线

const EditProduct = require('./components/EditProduct').default;
{ 
    path: '/edit/product/:id',component: EditProduct,name: 'edit-product'
}

我的 EditProduct 组件

<template>
    <div>
        <h1>this.$route.params.id</h1>
    </div>
</template>

干杯

解决方法

尝试在您的 EditProduct 组件中定义一个计算属性以获取产品 ID

computed: {
  productId(){
    return this.$route.params.id
  }
}

并在您的 productId 标签中使用 <h1>

<template>
    <div>
        <h1>{{ productId }}</h1>
    </div>
</template>

更新

solution :

将此观察器添加到您的 EditProduct 组件以对参数更改做出反应

watch: {
  $route(to) {
    console.log(to.params.id)
    // you can call your method here and pass product id to them for example:  this.getProductDetails(to.params.id)
  },beforeRouteEnter (to,from,next) {
  next(vm => { 
     //also call your method here =>  vm.getProductDetails(to.params.id)
  });
},

您可以在此处阅读有关参数更改的更多信息:Reacting to Params Changes

,

看看这个答案。您必须查看 productId 并再次执行您的逻辑。

Possible solution