vue中keep-alive,include的緩存問題
前提:有A,B,C,D四個頁面,A是按鈕頁(點擊按鈕進入B頁面),B是訂單列表頁,C是訂單詳情頁,D是費用詳情頁
需求:順序是A->B->C->D,每次都刷新頁面,D->C->B時走緩存,但是每次從A到B都要刷新B頁面,從B到C需要刷新C頁面,從C到D要刷新D頁面
在vue官方文檔2.1以上有include 和 exclude 屬性允許組件有條件地緩存。在這里主要用include結合vuex來實現(四個頁面組件都有自己的name才會生效,這里name就叫A,B,C,D)
從D->C,從C->B,從B->A 可以寫一個公共的頭部返回組件,統(tǒng)一使用 this.$router.go(-1)返回前一頁
App.vue
<template>
<div class="app">
<keep-alive :include="keepAlive" >
<router-view/>
</keep-alive>
</div>
</template>
<script type='text/javascript'>
export default {
data () {
return {}
},
computed: {
keepAlive () {
return this.$store.getters.keepAlive
}
}
}
</script>
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
keepAlive: []
},
mutations: {
SET_KEEP_ALIVE: (state, keepAlive) => {
state.keepAlive = keepAlive
}
},
getters: {
keepAlive: state => state.keepAlive
}
})
每次進入B頁面時先初始化 keepAlive(設置要走緩存的頁面)
A.vue
<script>
export default {
name: 'A',
methods: {
buttonClick () {
this.$store.commit('SET_KEEP_ALIVE', ['B', 'C', 'D'])
this.$router.push('/B')
}
}
}
</script>
B.vue 該頁面用來設置緩存和清除緩存
<script>
export default {
name: 'B',
beforeRouteEnter (to, from, next) {
next(vm => {
if (from.path.indexOf('C') > -1) {
vm.$store.commit('SET_KEEP_ALIVE', ['B'])
}
})
},
beforeRouteLeave (to, from, next) {
if (to.path.indexOf('C') > -1) {
this.$store.commit('SET_KEEP_ALIVE', ['B', 'C'])
} else if (to.path.indexOf('A') > -1) {
this.$store.commit('SET_KEEP_ALIVE', [])
}
next()
}
}
</script>
到這里就實現了需求
PS:vue keep-alive include無效
檢查版本
確定當前的vue版本的是2.1+
因為include和exclude是vue2.1.0新增的兩個屬性.
package.json
"vue": "^2.5.2",
檢查name
注意,不是router.js中的name,而是單個vue組件中的name屬性.
建議將router.js中的name和vue組件的name保持一致,不要混亂.
export default {
name: "index"
}
多層嵌套
網上的答案幾乎都是檢查vue組件的name屬性,但還是有一個巨坑.
那就是多級嵌套<router-view></router-view>,但凡有超過兩個以上的router-view且是父子級關系,請都加上keep-alive,只加一個不會生效.
// app.vue <keep-alive include="app,index"> <router-view></router-view> </keep-alive> // other.vue <keep-alive include="app,index"> <router-view></router-view> </keep-alive>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
解決vue 使用axios.all()方法發(fā)起多個請求控制臺報錯的問題
這篇文章主要介紹了解決vue 使用axios.all()方法發(fā)起多個請求控制臺報錯的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11
VUE的history模式下除了index外其他路由404報錯解決辦法
在本篇文章里小編給大家分享的是關于VUE的history模式下除了index外其他路由404報錯解決辦法,對此有需要的朋友們可以學習下。2019-08-08
vue3+vite使用vite-plugin-svg-icons插件顯示本地svg圖標的方法
這篇文章主要介紹了vue3+vite使用vite-plugin-svg-icons插件顯示本地svg圖標的方法,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-12-12

