Vue中返回页面不刷新之前页面–keep-alive的应用
1、若所有页面均需要保留缓存,返回时不刷新页面
则在App.vue文件中设置路由
<template>
<div id="app">
<keep-alive>
<router-view/>
</keep-alive>
</div>
</template>
2、若只是个别页面需要保留缓存则:
A:首先在App.vue中设置:
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
B:在router.js中设置:
import indexOne from '@/components/indexOne'
{
path: '/indexOne',
name: 'indexOne',
component: indexOne,
link: '/indexOne',
meta: {
keepAlive: true // 需要缓存
}
},
C:在详情页detail中,当引入keep-alive的时候,页面第一次进入,钩子的触发顺序created-> mounted->activated,退出时触发deactivated。当再次进入(前进或者后退)时,只触发activated。所以在详情页中需要添加activated和deactivated两个钩子函数来确定状态变化
//$route发生变化时再次赋值listId
watch: {
'$route'() {
this.listId = this.$route.params.id;
}
},
//通过activated钩子触发请求函数
activated() {
this.getDetail();
},
//返回详情页面时 隐藏内容div区块 再进入详情时 显示内容div区块
deactivated() {
this.isShowContent = false;
}
D:2019新发现:使用exclude属性不缓存模板组件即可,没有上面那么复杂了。
//不缓存detail组件
<keep-alive>
<router-view exclude="detail"></router-view>
</keep-alive>