Vuex 使用 v-model 配合 state的方法
v-model最好用的就是配合data達成Two-wayBinding,但若使用Vuex之後,是否還能使用v-model搭配state繼續Two-wayBinding呢?
Version
Vue2.5.17
Vuex3.0.1
V-modelvs.Data
HelloWorld.vue
{{name}}
Vue的v-model標準寫法,直接將綁定到namedata。
Valuevs.Input
但若將namedata提升到Vuex的namestate之後,就沒這麼簡單了。
Vuex強調的是UnidirectionDataflow,state只能被讀取,要寫入state必須靠mutation,因此v-model無法直接寫入state。
v-model本質是valuepropertybinding與inputevent的syntaticsugar,因此可以回歸基本動作,使用value與input實現。
HelloWorld.vue
{{name}}
第4行
將name綁定到value,將onInputName()綁定到inputevent。
16行
constcomputed=mapState(['name']);
從namestate建立namecomputed。
19行
constonInputName=function(e){ this.$store.commit('setName',e.target.value); };
定義onInputName(),負責接收inputevent,呼叫setNamemutations修改namestate。
store.js
importVuefrom'vue'; importVuexfrom'vuex'; Vue.use(Vuex); /**state*/ conststate={ name:'', }; /**mutations*/ constsetName=(state,payload)=>state.name=payload; constmutations={ setName, }; exportdefaultnewVuex.Store({ strict:true, state, mutations, });
很標準的Vuex寫法,由setNamemutation負責修改namestate。
這種寫法雖然可行,但似乎喪失了原本v-model的特色,又必須走回頭路使用event
V-modelvs.ComputedwithSetter
HelloWorld.vue
{{name}}
第4行
v-model回來了,但綁定的是namecomputed,而不是namedata。
14行
constname={ get(){ returnthis.$store.state.name; }, set(value){ this.$store.commit('setName',value); }, }
建立namecomputed,為了讓v-model能運作,特別將namecomputed加上setter。
- get():負責從namestate抓資料
- set():負責呼叫setNamemutation寫入state
透過有setter的computed,我們就能繼續使用v-model了。
Conclusion
雖然使用valuevs.input寫法也行,但v-modelvs.computedwithsetter寫法更優雅,實務上建議用此
SampleCode
完整的範例可以在我的GitHub上找到
Reference
Vuex,FormHandling
总结
以上所述是小编给大家介绍的Vuex使用v-model配合state的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!