一、問題描述
描述:頁面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); } }