需求: 页面顺序,从A到B到C,对于B 页面,进入C页面时,需要缓存,进入A页面时,不需要缓存,A进入B的时候是要刷新的。所以,问题就是,如何让keep-alive 缓存动态进行?
思路就是: 动态改变keep-alive的include数组。
- 首先创建A,B,C页面
-----a.vue
<template>
<div>
<div @click="handleGo">a页面</div>
<input />
</div>
</template>
<script>
export default {
name: "aaa",
methods: {
handleGo() {
this.$router.push({ path: "/b" });
},
},
};
</script>
-----b.vue
<template>
<div>
<div @click="handleGo">b页面</div>
<input />
</div>
</template>
<script>
export default {
name: "bbb",
methods: {
handleGo() {
this.$router.push({ path: "/c" });
},
},
};
</script>
-----c.vue
<template>
<div>
<div @click="handleGo">c页面,返回</div>
<input />
</div>
</template>
<script>
export default {
name: "ccc",
methods: {
handleGo() {
this.$router.go(-1);
},
},
};
</script>
- router.js文件(路由)配置当前页面的路由
import Vue from 'vue'
import VueRouter from 'vue-router'
import A from '../views/a.vue';
import B from '../views/b.vue';
import C from '../views/c.vue';
import store from '../store';
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'aaa',
component: A,
meta: {
noCache: false
}
},
{
path: '/b',
name: 'bbb',
component: B,
meta: {
noCache: false
}
},
{
path: '/c',
name: 'ccc',
component: C,
meta: {
noCache: false
}
},
]
const router = new VueRouter({
mode: 'history',
routes
})
export default router
- 配置store(vuex)
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
keepAliveComponents: []
},
mutations: {
keepAlive(state, component) {
!state.keepAliveComponents.includes(component) && state.keepAliveComponents.push(component);
},
noKeepAlive(state, component) {
const index = state.keepAliveComponents.indexOf(component);
index !== -1 && state.keepAliveComponents.splice(index, 1);
}
},
actions: {},
modules: {}
})
- App.vue(包裹所以页面的,也可以是其他的.vue文件)
<template>
<div>
<keep-alive :include="keepAliveComponents">
<router-view></router-view>
</keep-alive>
</div>
</template>
<script>
export default {
computed: {
keepAliveComponents() {
return this.$store.state.keepAliveComponents;
},
},
};
</script>
- 现在就在路由上监听是否缓存了,用路由守卫
-----router.js(路由文件)
import Vue from 'vue'
import VueRouter from 'vue-router'
import A from '../views/a.vue';
import B from '../views/b.vue';
import C from '../views/c.vue';
import store from '../store';
Vue.use(VueRouter)
const routes = [
.... 这里的代码跟上面的router.js一样
]
const router = new VueRouter({
..... 这里的代码跟上面的router.js一样
})
router.beforeEach((to, from, next) => {
if (!to.meta.noCache) {
store.commit('keepAlive', to.name);
}
next();
});
export default router
- 现在B跳转到C可以缓存,B跳A就不缓存,用路由独享守卫
-----b.vue
<template>
<div>
.....
</div>
</template>
<script>
export default {
name: "bbb",
methods: {
handleGo() {
.....
},
},
beforeRouteLeave(to, from, next) {
if (to.name !== "ccc") {
this.$store.commit("noKeepAlive", from.name);
}
next();
},
};
</script>
你们代码复制一下,运行一下就可以实现了。 重要的事情说三遍:**注意看注释!注意看注释!注意看注释!**不然你不知道怎么写的。 有用记得三连!拒绝白嫖!
|