Vue keep-alive组件的使用以及清除缓存的方法

1. keepAlive

在router的js文件中加入keepAlive

{
	path: "/A",
	name: 'A',
	meta:{ 
    	name: 'A' ,
   		keepAlive: false ,
	},
    component: resolve => require(['../A.vue'], resolve)
},
{
    path: "/B",
    name: 'B',
    meta:{ 
   		name: 'B' ,
   		keepAlive: true ,
   	},
    component: resolve => require(['../B.vue'], resolve)
},
{
    path: "/C",
    name: 'C',
    meta:{ 
   		name: 'C' ,
   		keepAlive: false,
   	},
    component: resolve => require(['../C.vue'], resolve)
},

在APP.vue中加入以下代码

<keep-alive>
	<router-view v-if="$route.meta.keepAlive" />
</keep-alive>
<router-view v-if="!$route.meta.keepAlive" />

2. 清除缓存的几种方法

有A,B,C三个组件需要在B组件中加入缓存,从组件B跳转组件C再从组件C跳转组件B缓存保留,但从组件B跳转到组件A后将组件B的缓存清除。

第一种用直接暴力法,在组件切换之后直接刷新

在组件B中加入beforeRouteLeave()方法和Watch监听事件

watch: {
	$route(to, from) {
		if(from.name === 'A'){
			this.route = from.name
			//如果是组件A跳转到的组件B,将组件B刷新
			this.$router.go(0);
		}
	},
},
//组件B跳转后将组件B的 keepAlive 值设置为false
beforeRouteLeave(to, from, next) {
	from.meta.keepAlive = false
	next()
}

组件B跳转到组件C组件B的缓存不清除,在组件C中加入beforeRouteLeave()方法

beforeRouteLeave (to, from, next) {
	//若从组件C跳转到组件B, 将组件B的 keepAlive 值为true
	to.meta.keepAlive = true
	next()
}

第二种方法用$vnode方法获取DOM元素,将缓存清除

组件B中加入beforeRouteLeave()方法

beforeRouteLeave(to, from, next) {
	if (to.path == "/C") { //这里的路径是要跳转的需要缓存的路径
		from.meta.keepAlive = true;
	} else {
		let Vnode = this.$vnode;
		let parentVnode = Vnode && Vnode.parent;
		if (parentVnode && parentVnode.componentInstance && parentVnode.componentInstance.cache) {
			var key = Vnode.key == null ? Vnode.componentOptions.Ctor.cid + (Vnode.componentOptions.tag ? `::${Vnode.componentOptions.tag}` : '') : Vnode.key;
			var cache = parentVnode.componentInstance.cache;
			var keys  = parentVnode.componentInstance.keys;
			if (cache[key]) {
				this.$destroy();
				if (keys.length) {
					var index = keys.indexOf(key);
					if (index > -1) {
						keys.splice(index, 1);
					}
				}
				cache[key] = null;
			}
		}
	}
	next();
}

在组件C中加入beforeRouteLeave()和beforeRouteEnter()方法

data(){
	return{
		Fromvnode: null
	}
}
beforeRouteEnter(to, from, next) {
	next(vm => {
		vm.Fromvnode = from
	})
},
beforeRouteLeave(to, from, next) {
	if (to.path !== '/B') {
		this.Fromvnode.meta.keepAlive = false
	}
	next()
}

你可能感兴趣的:(前端,vue.js,缓存,前端)