Vue路由监听

一、问题描述

描述:页面1showowner.vue跳转到页面2showuser.vue

需求:页面1的多个结点对应于一个页面2文件【页面2未展示】

问题:并不是页面一的一个结点对应一个页面二文件

处理:路由监听

二、代码:

页面一

 handleNodeClick(data) {
      console.log(data);
      //每次点击结点都要初始化ownerId
      this.domId = data.data.domId;
      this.ownerId = data.data.ownerId;
      this.varify();
      this.$router.push({
        path: this.pathVariable,
        query: {
          domId: this.domId,
          ownerId: this.ownerId
        }
      });
       
    }

页面二

watch:{
  // ownerId(val,oldVal){
  //   console.log(val);
  //   this.getLeft();
  // },
  $route(to,from){
    console.log(to.path);
    this.getLeft();
  }
},

 
 
  methods: {
    //获取左边参数,利用获得的参数从后端取数据
    getLeft() {
      alert(1111);
      // this.domId = this.$route.query.domId;
      // console.log(this.domId);
      // this.ownerId = this.$route.query.ownerId;
      // console.log(this.ownerId);
      this.domId = this.$route.query.domId;
      this.ownerId = this.$route.query.ownerId;
      axios
        .get("/api/queryusers/" + this.domId + "?ownerId=" + this.ownerId, {
          headers: { Validate: "123456" }
        })
        //then获取成功;response成功后的返回值(对象)
        .then(response => {
          // console.log(response);
          // console.log(response.data.data);
          this.tableData = response.data.data;
          // console.log(response.data.data.childList);
          // console.log(this.data1);
        })
        //   获取失败
        .catch(error => {
          console.log(error);
          alert("网络错误,不能访问haha");
        });
    },
}
 

我遇到的问题是路由携带页面1的参数,点击不同结点参数不一样,对应于页面二展示的数据(从后端获取)不一样;

但是页面二是一个vue文件。

watch:{
  // ownerId(val,oldVal){
  //   console.log(val);//val即newVal
  //   this.getLeft();
  // },
},

http://localhost:8080/#/showuser?domId=1&ownerId=1

http://localhost:8080/#/showuser?domId=1&ownerId=4

这段注释掉的代码没有监听到路由的变化,是因为vue认为上面的两种路由的HTTP地址是同一个路由,参数变化并不认为是路由变化,因为归根到底还是同一个showuser.vue故而没有监听到变化,不会重新调用新的this.getLeft();

解决方法:如果我们要在路由发生变化的时候执行方法,那我们就需要监听$route的变化,在它变化的时候执行方法。即

watch:{
  $route(to,from){
    console.log(to.path);//当前页面path即/showuser
    this.getLeft();
  }
},

三、另外几种监听路有变化的方法

1.handler;当然,如果我们要通过判断路由发生的特定变化来执行方法,可以使用handler

// 监听,当路由发生变化的时候执行
watch: {
  $route: {
    handler: function(val, oldVal){
      console.log(val);
    },
    // 深度观察监听
    deep: true
  }
},
watch:{
  "$route":{
    handler(route){
      const that=this;
      if(route.name=='Hello'){
        that.fetchData();
      }
    }
  }
}

2.在Vue的官方文档中,直接在监听后传入一个方法对应的字符串,在路由发生变化的时候自动执行方法

// 监听,当路由发生变化的时候执行
watch: {
  '$route':'getPath'
},
methods: {
  getPath(){
    console.log(this.$route.path);
  }
}

猜你喜欢

转载自www.cnblogs.com/yanl55555/p/11995938.html