main.js中的代码
<template>
<div id="app">
<keep-alive :include="cachePages" :max="15">
<router-view :key="key"/>
</keep-alive>
</div>
</template>
<script>
export default {
name: 'App',
components: {},
data() {
return {
//页面缓存栈
cachePages: []
}
},
computed: {
key() {
return this.$route.path
},
},
watch: {
$route: {
immediate: true,
handler(route) {
//实现栈内单例
const nowPage = route.name
const indexOf = this.cachePages.indexOf(nowPage)
console.log('cachePages: ' + this.cachePages)
if (indexOf === -1) {
console.log('不包含')
this.cachePages.push(nowPage)
} else {
console.log('包含')
this.cachePages = this.cachePages.slice(0, indexOf + 1)
}
console.log('cachePages: ' + this.cachePages)
},
},
},
}
</script>
没错就是这么简单
原理的话,就是创建了一个页面的缓存栈cachePages,当route发生改变是,动态的修改cachePages:如果新route不包含在栈内就入栈,包含的话就退栈,退到当前route。
下面是凑字数测试流程
const routes = [ //路由配置,配置路由路径与组件的对应关系
{
path: '/',
redirect: '/a'
},
{
path: '/a',
name: 'AComponent',
component: () => import('../src/components/AComponent.vue')
},
{
path: '/b',
name: 'BComponent',
component: () => import('../src/components/BComponent.vue')
},
{
path: '/c',
name: 'CComponent',
component: () => import('../src/components/CComponent.vue')
},
]
const router = new VueRouter({ //新建路由实例
routes,
})
创建了三个页面
A:
<template>
<div>
A
<button @click="$router.push('/a')">跳转到A</button>
<button @click="$router.push('/b')">跳转到B</button>
<button @click="$router.push('/c')">跳转到C</button>
</div>
</template>
<script>
export default {
name: 'AComponent',
}
</script>
B:
<template>
<div>
B
<button @click="$router.push('/a')">跳转到A</button>
<button @click="$router.push('/b')">跳转到B</button>
<button @click="$router.push('/c')">跳转到C</button>
</div>
</template>
<script>
export default {
name: "BComponent"
}
</script>
C:
<template>
<div>
C
<button @click="$router.push('/a')">跳转到A</button>
<button @click="$router.push('/b')">跳转到B</button>
<button @click="$router.push('/c')">跳转到C</button>
</div>
</template>
<script>
export default {
name: "CComponent"
}
</script>
这边进行了从A到B到C再回到A的操作,可以看到B和C的缓存确实是被清除了
水完了,开心