-
概念:组件切换时保存状态,防止重新渲染dom元素
-
实现方式
1、使用meta路由元信息
-
需求:A-->B不缓存B,B-->C缓存B
- router.js
import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
const router=new Router({
mode:"history",
route:[
{
path:"/A",
component:()=>import("@/pages/A.vue")
},
{
path:"/B",
component:()=>import("@/pages/B.vue"),
meta:{
keepAlive:true,
}
},
{
path:"/C",
component:()=>import("@/pages/C.vue")
}
]
})
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
<template>
<div>
<button @click="toGoods()"></button>
</div>
</template>
<script>
export default{
data(){
return{}
},
methods:{
toGoods(){
this.$router.push("/B")
}
}
}
</script>
<template>
<div>
<button @click="toGoodsDetail()">{{name}}</button>
</div>
</template>
<script>
export default{
data(){
return{
name:"商品"
}
},
beforeRouteLeave(to,from,next){
if(to.path=="/C"){
from.meta.keepAlive=true;
}else{
from.meta.keepAlive=false;
}
next();
},
methods:{
toGoodsDetail(i){
let _this=this;
_this.$router.push("/C");
_this.goods="goods";
}
}
}
</script>
<template>
<div>
<h1>商品</h1>
</div>
</template>
<script>
export default{
data(){},
methods:{
}
}
</script>
- 问题
只会缓存第一次进入B时的状态,不会缓存重新请求的数据,如果只需要缓存第一次时的状态,可以使用