Vuex动态注册模块state保留旧值问题
发布于 3 年前 作者 huaer 1430 次浏览 来自 问答
粉丝福利 : 关注VUE中文社区公众号,回复视频领取粉丝福利

目前专案使用动态注册模块,有卸载模块,但再次注册模块时,之前模块的State还保留之前的数据,需求上并没有要保留state。

目前是这样写:

// module.js
import Vue from 'vue';

const state = {
	a: '',
	b: '',
	c: ''
}
const getters = { ... };
const mutations = { ... };
const actions = { ... };

export default {
	namespaced: true,
	state () { return state; },
	getters,
	mutations,
	actions
};

于使用页面 Component

// page.vue 的 <script>
import Module from './module.js';
export default {
	...
	beforeCreate () {
		// 注册模块
		this.$store.registerModule('modulename', Module);
	},
	beforeDestroy () {
		// 卸载模块
		this.$store.unregisterModule('modulename');
	},
	...
}

操作时更改Module的State

state.a = 'AAA'

离开此页面再回来时,state没有回到原本的 module.js,希望module呈现:

state.modulename = {
	a: '',
	b: '',
	c: ''
}

请问是哪里有错吗?

回到顶部