由于vuex state定义的变量只能在 mutations中修改,因此表单中的v-model绑定就会有问题,解决方案vue
... <input type="text" v-model="username" /> ... computed: { username: { // 双向绑定 input 因为vuex中的数据只能在 mutations中修改,因此当username数据发生变化的时候调用vuex文件中的方法 get () { return this.$store.username }, set (value) { this.$store.commit('mutations_username', value) } } ...
store/index.js文件vuex
... state: { username: '', state: { show: true, dialog: true, formInfo: { username: ['zxc', 'hp'], email: '', password: '', passwordSure: '', address: '', number: 0, total: 0, search: '', searchResult: [] } }, ... }, mutations: { mutations_username (state) { state.username = 'zhangxuchao' } ...
使用 mapState mapMutations mapActionsthis
... import { mapState, mapMutations, mapActions } from 'vuex' ... methods: { ...mapMutations({ 'switch_show': 'switch_show', 'switch_dialog': 'switch_dialog', 'filterFun': 'filterFun' }), ...mapActions({ 'actions_show': 'actions_show' }) }, computed: { // 从vuex文件中导入数据,至关于data中的饿数据 ...mapState({ formInfo: state => state.recommend.formInfo, dialog: state => state.recommend.dialog, show: state => state.recommend.show }), search: { // 双向绑定 input 因为vuex中的数据只能在 mutations中修改,因此当formInfo数据发生变化的时候调用vuex文件中的方法 get () { return this.formInfo.search }, set (value) { // this.$store.commit('filterFun', value) this.filterFun(value) } } }