轉載自:https://www.cnblogs.com/dansingal/p/8302100.html
問題描述:
在keep-alive中的在跳轉到指定的路由時刷新對應的路由,其余不刷新。
1
2
3
4
5
|
<transition name=
"fade"
mode=
"out-in"
>
<keep-alive>
<router-view></router-view>
</keep-alive>
</transition>
|
有幾種解決方式:
1.在keep-alive中直接添加 include,cachedViews(Array類型:包含vue文件的組件name都將被緩存起來);反之exclude則是不包含;
注意:所有.vue組件文件都必須附上name屬性!!!建議用vuex管理cachedViews
1
2
3
|
<keep-alive :include=
"cachedViews"
>
<router-view></router-view>
</keep-alive>
|
2.監測$router的變化;
1
2
3
4
|
watch: {
// 如果路由有變化,會再次執行該方法
"$route"
:
"fetchDate"
}
|
但是會在頁面離開時再次執行fetchDate,並不是我們需要的,所以可以在to和from上添加執行邏輯,但也是十分的麻煩
1
2
3
4
5
6
7
8
|
//$router是只讀狀態,所以賦值操作會失效
watch: {
$route (to, from) {
if
(list.indexOf(from.path) > -1){
//自行添加邏輯,list為你不想有緩存的路徑
this
.getData()
}
}
}
|
3.在添加keep-alive后會增加兩個生命周期mounted>activated、離開時執行deactivated,路由的進入和切換回相應的觸發activated和deactivated,這樣就可以在每次入路由執行更細致的操作了
1
2
3
4
5
|
//如果是服務端渲染就算了
activated() {
//只刷新數據,不改變整體的緩存
this
.fetchDate();
}
|
4.還有更簡單粗暴的
1
2
3
4
5
6
|
//我就笑笑不說話<br><div>
<keep-alive>
<router-view v-
if
=
"$route.meta.keepAlive"
></router-view>
</keep-alive>
<router-view v-
if
=
"!$route.meta.keepAlive"
></router-view>
</div>
|
5.還有種情況,在不同路由應用了相同的vue組件
1
2
|
{path:
'aaa'
,component:Mompage,name:
'mom'
},
{path:
'bbb'
,component:Mompage,name:
'momPlus'
}
|
默認情況下當這兩個頁面切換時並不會觸發vue的created或者mounted鈎子,需要手動的watch:$router(又回到上面的步驟),或者在router-view上加上唯一值。
1
2
3
4
5
6
7
|
//隨便抄一段代碼過來
<router-view :key=
"key"
></router-view>
computed: {
key() {
return
this
.$route.name !== undefined?
this
.$route.name + +
new
Date():
this
.$route + +
new
Date()
}
}
|