vue A、B、C三個頁面keepAlive、include頁面緩存問題

背景:
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>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容