vue 复用组件,打开两个标签页时, 数据不更新解决办法

本文解析了Vue中使用路由参数时组件复用导致的数据不更新问题,并提供了两种解决方案:通过watch监听$route变化重新获取数据,或为<router-view>绑定唯一key触发组件重新加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue官网原话:提醒一下,当使用路由参数时,例如从 /user/foo 导航到 /user/bar,原来的组件实例会被复用。因为两个路由都渲染同个组件,比起销毁再创建,复用则显得更加高效。不过,这也意味着组件的生命周期钩子不会再被调用。
这就是为什么打开两个或多个详情页的时候,切换标签页数据不更新的原因。
解决方法:
1: watch (监测变化) $route 对象:

<router-link
    :to="{path:'/intention_manage/intention_detail',query:{id:scope.row.inten_id}}"
>
   <el-button type="text">详情</el-button>
</router-link>

watch: {
    $route(to, from) {
      this.id = to.query.id;
      this.getData(); // 再次获取数据
    }
  },
  methods: {
    getData() {
      this.$post("/intent/getintentiondetail", { inten_id: this.id }).then(
        res => {
          if (res.code == 200) {
            this.params = res.result.intent_detail;
          } else {
            this.$message.error(res.msg);
          }
        }
      );
    }
 }

2:可以绑定唯一的key

<router-view :key="key"></router-view>
computed: {
    key() {
        return this.$route.name !== undefined? this.$route.name + new Date(): this.$route + new Date()
    }
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值