做vue项目时,有时要在某些页面做缓存,而其它页面不要。比如:A:首页,B:获取所有订单页面,C:订单详情页面;从A(首页)进入 B(获取所有订单)时应该不缓存,B(所有订单)进入 C(订单详情)订单后时再返回B,此时B(所有订单页面)缓存。不需要再次刷新,即:A->B->C时都是刷新,而C->B->A时B缓存。在vue官方文档2.x以上有include
和 exclude
属性允许组件有条件地缓存。在这里主要用include结合vuex来实现,include 是根据组件的name值来判断的,所以三个页面组件都有自己的name才会生效(重要是B必须有name),这里name就叫A,B,C。
首先安装vuex
npm install --save vuex
安装后新建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;
import store from './store' new Vue({ el: '#app', // 注入 store store, router, components: { App }, template: '<App/>', })
在APP.vue页面加入keepalive动态判断
<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>
在A(首页)进入 B时
<script> export default { name: 'A', methods: { goB() { this.$store.commit('setKeepAlive', ['B']) //设置缓存 this.$router.push('/B') } } } </script>
在B页面设置是否缓存
<script> export default { name: 'B',//组件名称 beforeRouteLeave (to, from, next) { if (to.path.indexOf('C') > -1) { this.$store.commit('setKeepAlive', ['B']) } else { this.$store.commit('setKeepAlive', []) } next() } } </script>
这样就可以了。