Vue 缓存机制

Vue 缓存机制 1. 在 store.js 中设置全局的 数据存储字段// 是否缓存keepAlivePage:[],mutations CHANGE_KEEP_ALIVE(state,data){state.keepAlivePagedata},actions:{//类似 mothods异步// 页面缓存setKeepAlivePage({commit},data){commit(CHANGE_KEEP_ALIVE,data)},}2.在 自定义的 set.js 中设置全局方法importmomentfrommomentexportdefault{install(Vue){// 增加缓存页面Vue.prototype.addKeepAlivefunction(componentName){letalivePagethis.$store.state.keepAlivePage.slice(0)alivePage.push(componentName)alivePageArray.from(newSet(alivePage))this.$store.dispatch(setKeepAlivePage,alivePage)console.log(this.$store.state.keepAlivePage,当前缓存的页面1)}// 删除缓存页面Vue.prototype.deleteKeepAlivefunction(componentName){letalivePagethis.$store.state.keepAlivePage.slice(0)alivePage.forEach((item,index){if(itemcomponentName){alivePage.splice(index,1)}})alivePageArray.from(newSet(alivePage))this.$store.dispatch(setKeepAlivePage,alivePage)console.log(this.$store.state.keepAlivePage,当前缓存的页面2)}}}3.在 App.vue 中设置缓存keep-alive:includekeepAlivePagerouter-view/router-view/keep-alivecomputed:{...mapState([keepAlivePage]),},4. 在页面中使用beforeRouteLeave(to,from,next){const_thisthis;console.log(to.name,from.name,beforeRouteLeave)// 如果跳转到详情页面走缓存if(to.nameproductetails){_this.addKeepAlive(from.name);}else{_this.deleteKeepAlive(from.name);}next()},或者beforeRouteLeave(to,from,next){const_thisthis;// console.log(to.name, from.name, beforeRouteLeave)// console.log(_this.$options.name, beforeRouteLeave)// 如果跳转到详情页面走缓存if(to.nameupcomplaintDetail||to.namestoreexamine||to.namedealerexamine||to.namesbuexamine||to.namemasterexamine){_this.addKeepAlive(_this.$options.name);}else{_this.deleteKeepAlive(_this.$options.name);}next()},