1. 程式人生 > >巢狀路由之間的傳值,go(-1)並同時傳參

巢狀路由之間的傳值,go(-1)並同時傳參

巢狀路由子路由向父路由傳值方式就是父子元件之間的傳值方式,即使用emit。
如果是想看go(-1)的同時傳值,直接到文末

假設現在有路由如下:
A是父路由,BC是子路由

{
    path: '/A',
     name: 'A',
     component: require('@/components/test/A').default,
     children: [
         {
             path: '/B',
             name: 'B',
             component: require('@/components/test/B').default
}, { path: '/C', name: 'C', component: require('@/components/test/C').default }, ] },

1、巢狀路由一個跳轉傳值的套路如下:

A.vue :
在template中需加上router-view,來渲染你指定路由對應的元件,這樣就是B和C了。

<template>
    <div class="A">
		 <router-
view></router-view> </div> </template> 跳轉至B: this.$router.push({name:'B',params:{info:info}});

B.vue中:
B實際上是載入在router-view這個容器中的,還是屬於A頁面的一部分,所以要只看到B,需設定樣式如下:

 .B {
        position: absolute;
        bottom: 0;
        left: 0;
        z-index: 100;
        width: 100%;
        height
: 100vh; }
在B中,跳轉到C:
this.$router.push({name:'C',params:{info:info}});

2、實現C跳轉回A.vue並帶參

C.vue中:

 //依舊是元件傳值的方式
 this.$emit("selectGoods",this.selectGoods);
 this.$router.go(-2); //回退兩步,即回到A

這種寫法不知道好不好,但百試不爽呀!!

A.vue中:
給router-view新增一個回撥事件

<router-view @selectGoods="selectGoodsBack"></router-view>

selectGoodsBack(value){
	console.log(value); //就是上面的selectGoods的值
}

這樣A就獲取了C的值。

如果A中的資料需重新整理,可通過重新請求,改變資料;
也可以強制重新整理:(不建議這麼幹!)

window.location.reload();
如果需要href改變:
就直接 window.location.replace(url); 或者 window.location.href = url;

selectGoodsBack(value){
    console.log('子路由返回:',value);
	//this.$router.replace('/sellerSetting?active=1'); //無效
	//強制重新整理 
    let url = window.location.href.split('dist')[0];
    window.location.replace( url+"dist/sellerSetting?active=1");

}

3、總結:

1、記錄一下巢狀路由寫程式碼時的套路
2、父子路由的傳值
3、子路由回到父路由重新整理,重新請求資料,以後就這麼幹吧,如果是刪除,直接陣列移除這條資料,不重新整理。如果增加,就重新請求,只改變陣列的值。

子路由:
 this.$emit('addMemberBack', 1);  //給父路由傳值,讓父路由重新請求資料
 this.$router.go(-1);  //返回父路由

父路由:
<router-view @addMemberBack="addMemberBack"></router-view>
selectGoodsBack(){
//重新向後臺請求資料
}