背景:
1、A列表頁面 --- 跳轉(zhuǎn)到 --- B填寫頁面 (B頁面不要緩存)。
2、A列表頁面 --- 跳轉(zhuǎn)到 --- B填寫頁面(填寫了內(nèi)容) --- 跳轉(zhuǎn)到(B頁面需要緩存) --- C選擇單位頁面再回到B頁面,要顯示 B頁面之前填寫的內(nèi)容。
用vue-router中的keepAlive設(shè)置為true是不可行的。
// ********app.vue文件*******
<div id="app">
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
// ********router.config.js文件*******
{
path: '/A',
name: 'A',
component: () =>import ('@/views/A'),
meta: {
title: 'A列表頁面',
keepAlive: false
}
},
{
path: '/B',
name: 'B',
component: () =>import ('@/views/B'),
meta: {
title: 'B填寫頁面',
keepAlive: true // 設(shè)置B頁面緩存
}
},
{
path: '/C',
name: 'C',
component: () =>import ('@/views/C'),
meta: {
title: 'C單位選擇頁面',
keepAlive: false
}
}
// 在B填寫頁面攔截路由跳轉(zhuǎn),動態(tài)修改B填寫頁面的緩存
beforeRouteLeave(to, from, next) {
if (to.name === 'C') {
from.meta.keepAlive = true // 跳轉(zhuǎn)C單位選擇頁面,設(shè)置B填寫頁面(本頁面)緩存
}else{
from.meta.keepAlive = false // 跳轉(zhuǎn)A列表頁面,設(shè)置B填寫頁面(本頁面)不緩存
}
next()
},
注:::::以上這種方式是不行的。
可行方案:
結(jié)合keep-alive的include屬性和vuex進行緩存。

image.png
首先安裝vuex
安裝后新建store.js
// ********store.js文件*******
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
export default new Vuex.Store({
state: {
keepAlive: []
},
mutations: {
setKeepAlive: (state, keepAlive) => {
state.keepAlive = keepAlive
}
},
getters: {
keepAlive: state => state.keepAlive
}
})
//在main.js里面引入store.js
// ********main.js文件*******
import store from './store'
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
// ********app.vue文件*******
<div id="app">
<keep-alive :include="keepAlive">
<router-view></router-view>
</keep-alive>
</div>
<script>
export default {
name: 'MainView',
computed: {
keepAlive() {
return this.$store.getters.keepAlive
}
}
}
</script>
// ********A列表頁面.vue文件*******
// 在A列表頁面點擊進入 B填寫頁面時
this.$store.commit('setKeepAlive', ['B']) // 設(shè)置B填寫頁面緩存
this.$router.push('/B') // 跳轉(zhuǎn)B填寫頁面
// ********B填寫頁面.vue文件*******
// B填寫頁面的跳轉(zhuǎn)路由攔截方法
beforeRouteLeave (to, from, next) {
if (to.name === 'C') { // 如果跳轉(zhuǎn)是C單位選擇頁面,那就把當(dāng)前B填寫頁面緩存起來。
this.$store.commit('setKeepAlive', ['B'])
} else {
this.$store.commit('setKeepAlive', []) // 跳轉(zhuǎn)其它頁面則清除緩存
}
next()
}
這種方式不依賴于vue-router中的keepAlive值,那怕設(shè)置為false,也可以通過上面的方式進行頁面緩存。
這樣就OK了!?。?/p>