vue3中include绑定数组方式keep-alive失效的解决方案

1,324 阅读1分钟

image.png 如图所示,每个标签页都有自己的标签页,使用keep-alive缓存,标签页切换时不会销毁与创建组件。 html代码部分:

<router-view v-slot="{ Component }">
        <keep-alive :include="$store.state.common.keepAliveComponents">
                <component :is="Component"></component>
        </keep-alive>
</router-view>`

使用vuex缓存include数组部分:

export default {
	state: {
		keepAliveComponents: ["Home"],
	},
	mutations: {
		keepAlive(state, component) {
			!state.keepAliveComponents.includes(component) && state.keepAliveComponents.push(component);
		},
		noKeepAlive(state, component) {
			const index = state.keepAliveComponents.indexOf(component);
			index !== -1 && state.keepAliveComponents.splice(index, 1);
		},
	},
};

vue2里这样做是没有问题的,vue中不支持对绑定的include数组(keepAliveComponents)直接操作,而是操作数组后返回新数组给include,解决方案很简单,只需要加一句代码:

export default {
	state: {
		keepAliveComponents: ["Home"],
	},
	mutations: {
		keepAlive(state, component) {
			!state.keepAliveComponents.includes(component) && state.keepAliveComponents.push(component);
		},
		noKeepAlive(state, component) {
			const index = state.keepAliveComponents.indexOf(component);
			index !== -1 && state.keepAliveComponents.splice(index, 1);
			//vue3中需要返回全新的数组给include
			state.keepAliveComponents = JSON.parse(JSON.stringify(state.keepAliveComponents));
		},
	},
};