由於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) } } }