应用场景
如果未使用 keep-alive 组件,则在页面回退时仍然会重新渲染页面,触发 created 钩子,使用体验不好。
在以下场景中使用 keep-alive 组件会显著提高用户体验,菜单存在多级关系(如:主页 -> 列表页 -> 详情页)的场景:
当从主页跳转列表页时,列表页组件重新渲染;
当从详情页返回列表页时,列表页组件缓存 不重新请求数据;
// app.vue
<template>
<div id="app">
<keep-alive :include="keepAliveInclude">
<router-view/>
</keep-alive>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
name:'home',
computed:{
...mapGetters([
'keepAliveInclude',
])
},
}
</script>
store 中对 keepAliveInclude 的状态更新保存
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
// keepAlive缓存组件
keepAliveInclude:[],
},
getters:{
keepAliveInclude: state => state.keepAliveInclude,
},
mutations: {
SET_KEEPALIVEINCLUDE:(state, keepAliveInclude) => {
state.keepAliveInclude = keepAliveInclude;
}
},
actions: {
setKeepAliveInclude({ commit }, keepAliveInclude){
commit("SET_KEEPALIVEINCLUDE", keepAliveInclude)
},
},
})
需要进行缓存的页面 list.vue
<template>
<div>
<button @click="goHome">主页</button>
<button @click="goDetail">详情</button>
列表: <input type="text" v-model="inputVal">
</div>
</template>
<script>
export default {
name:'list',
data(){
return {
inputVal:'',
}
},
methods:{
goDetail(){
this.$router.push('./detail')
},
goHome(){
this.$router.push('./home')
}
},
beforeRouteLeave (to, from, next) {
if(to.name == 'detail'){
this.$store.dispatch('setKeepAliveInclude',['list'])
}else{
this.$store.dispatch('setKeepAliveInclude',[])
}
// next();
setTimeout(() => { next(); }, 10); // next()需用定时器包裹,否则多次切换无法缓存
}
}
</script>