vue2 h5开发前进刷新后退缓存实现
在store定义变量
const state = {
includedComponents: []
}
const mutations = {
includedComponents (state, data) {
state.includedComponents = data
}
}
在app.vue(我这里主要在layout.vue修改)使用 keep-alive :include ,includedComponents 是仓库管理的状态
<template>
<div>
<van-nav-bar
v-show="showNav"
:title="pageTitle"
left-arrow
@click-left="onClickLeft"
class="nav-bar"
/>
<keep-alive :include="includeComponents">
<router-view></router-view>
</keep-alive>
</div>
</template>
<script>
import { getPageTitle } from '@/lang';
export default {
name: 'Layout',
computed: {
showNav() {
return !this.$route.meta.hideNav;
},
pageTitle() {
return getPageTitle(this.$route.meta.title);
},
includeComponents() {
return this.$store.state.includeComponents;
}
},
methods: {
onClickLeft() {
this.$router.back();
}
}
}
</script>
HistoryTask.vue需要缓存的页面
index.vue --> HistoryTask.vue,以此类推a–>b–>c–>d
HistoryTask.vue -->index .vue,必须销毁当前页面通过this.$destroy()实现d–>c–>b–>a
//页面离开时
beforeRouteLeave (to, from, next) {
//to.name是离开后进入的页面
if (to.name === 'SignRecord') {
this.$store.commit('task/includedComponents', 'HistoryTask') // 保存需要进行缓存的页面searchResult
next()
} else {
//点击返回时需要将状态设置为空
this.$store.commit('task/includedComponents', '')
//返回上一页必须销毁当前页面,不然重新进入页面会不刷新
this.$destroy()//销毁当前页面实例
next()
}
},
//页面进入时
activated () {
this.$store.commit('task/includedComponents', 'HistoryTask')
// console.log('activated')
},
deactivated () {
// console.log('deactivated')
},