微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Vue:params 值在创建的方法中不会改变

如何解决Vue:params 值在创建的方法中不会改变

我有这个带有参数的另一个组件的链接

<div class="dropdown-menu bg-light" aria-labelledby="navbarDropdown">
      <div v-for="category in categories" :key="category.id">
         <div v-if="lang=='ku'"><li><a class="dropdown-item font-weight-bold py-2" href="#" ><router-link :to="{name:'category',params:{id:category.id}}">{{category.catagory_ku}}</router-link></a></li></div>

          <div v-else><li><a class="dropdown-item font-weight-bold py-2" href="#" ><router-link :to="{name:'category',params:{id:category.id}}">{{category.catagory_ar}}</router-link></a></li></div> 
          </div>
     </div>

像这样的类别组件:

<template>
    <div style="margin-top:132px">
        Categories {{id}}
    </div>
</template>
<script>
export default {
data(){
    return {
        id :''
    }
},created(){
    this.id=this.$route.params.id
}
}
</script>

当我按下路由链接时,url 中的 id 值发生了变化,但在页面视图中,它只获取我单击的第一个 id 值,并且在我通过不同的 id 值单击另一个相同链接后不会更改

解决方法

尝试将 id 定义为计算属性:

<template>
    <div style="margin-top:132px">
        Categories {{id}}
    </div>
</template>
<script>
export default {
   computed:{
      id(){
        return this.$route.params.id
      }
 }
}
</script>

,

这应该在安装的钩子中

created(){
    this.id=this.$route.params.id
}
// replace with
mounted(){
    this.id = this.$route.params.id
}

此外,如果您想执行一些与 id 更改相关的额外操作,您可以watch 路由

<template>
    <div style="margin-top:132px">
        Categories {{ id }}
    </div>
</template>
<script>
export default {
data() {
    return {
        id: ''
    }
},mounted() {
    this.id = this.$route.params.id
},watch: {
    $route(to) {
      this.id = to.params.id
      // do other logics here
    }
}
</script>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。