【问题标题】:Component works only once using router-link - Laravel vue组件仅使用 router-link 工作一次 - Laravel vue
【发布时间】:2021-07-05 23:33:36
【问题描述】:

我正在做一个使用 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>

干杯

【问题讨论】:

  • 我更新我的答案看看

标签: vue.js vue-router laravel-vue


【解决方案1】:

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

Possible solution

【讨论】:

    【解决方案2】:

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

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

    并在您的&lt;h1&gt; 标签中使用productId

    <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

    【讨论】:

    • 上面写着_vm.productId is not a function
    • 是的,我错了,模板中productId后面的括号去掉
    • 哦,谢谢,我现在可以获取productId,但是我如何使用axios.get获取EditProduct中的产品详细信息,因为当我在方法上调用它时:它说`productId is not已定义。
    • 要访问computed 中的computed 属性,您应该在其前面加上this 关键字,例如:this.productId,然后您就可以访问产品ID
    • 还是一样,只工作一次,直到我刷新页面或点击其他链接:(
    猜你喜欢
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 2020-03-28
    • 2020-11-16
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多