使用vuex时 官方推荐使用commit才修改state数据。vue
save(state, { path, data }) { if (!path ) { throw new Error('need path') } const keyPath = path.split('.') let needSave = state for (let i = 0; i < keyPath.length - 1; i++) { needSave = needSave[keyPath[i]] if(!needSave) { throw new Error(`error path: ${keyPath[i]}`) } } needSave[keyPath[keyPath.length - 1]] = data } // 使用 vuex.commit('save', {path:'a.b.c', data:'我是须要保存的数据'}) state.a.b.c = '我是须要保存的数据' //组件中使用 //若是要双向绑定某个vuex中的值。 <input v-model="c"> //script computed: { c: { get(){ return vuex.state.a.b.c }, set(val) { vuex.commit('save', {path:'a.b.c',data: val}) } } }
这样就作到了在组件中双向绑定,而且使用commit改变state中的值,vuex使用严格模式也不会报错了。vuex