img

vue 路由参数变化,页面不刷新(数据不更新)解决方法

2020-09-30 0条评论 3.3k次阅读 JavaScript


路由参数改变,页面数据不更新解决方法:

http://localhost:8080/#test?id=1

http://localhost:8080/#test?id=2

参数切换后,数据未更新

以下为解决办法:

监听路由变化,若参数不相同,则重新加载数据,更新视图:

watch: {
      '$route' (to, from) { //监听路由是否变化
          if(to.query.id != from.query.id){
              this.id = to.query.id;
              this.init();//重新加载数据
          }
      }
},
created() {
    if(this.$route.query) {
        this.id = this.$route.query.id;
        this.init();
    }
},

路由跳转也可以通过 watch 这样解决

 watch: {
    $route(to) {
      this.routerName = to.name;
      this.routerBelongName = to.meta.belongGroup;
      console.log(this.routerBelongName,"watch")
    }
  },
  mounted() {
    this.routerName = this.$route.name;
    this.routerBelongName = this.$route.meta.belongGroup;
  }

💬 COMMENT


🦄 支持markdown语法

👋友