寫在前面
此系列來源于開源項(xiàng)目:前端 100 問:能搞懂 80%的請(qǐng)把簡(jiǎn)歷給我
為了備戰(zhàn) 2021 春招
每天一題,督促自己
從多方面多角度總結(jié)答案,豐富知識(shí)
雙向綁定和 vuex 是否沖突
簡(jiǎn)書整合地址:前端 100 問
正文回答
當(dāng)在嚴(yán)格模式中使用 Vuex 時(shí),在屬于 Vuex 的 state 上使用 v-model 會(huì)比較棘手:
<input v-model="obj.message">
假設(shè)這里的 obj 是在計(jì)算屬性中返回的一個(gè)屬于 Vuex store 的對(duì)象,在用戶輸入時(shí),v-model 會(huì)試圖直接修改 obj.message。在嚴(yán)格模式中,由于這個(gè)修改不是在 mutation 函數(shù)中執(zhí)行的, 這里會(huì)拋出一個(gè)錯(cuò)誤。
用“Vuex 的思維”去解決這個(gè)問題的方法是:給 <input> 中綁定 value,然后偵聽 input 或者 change 事件,在事件回調(diào)中調(diào)用一個(gè)方法:
<input :value="message" @input="updateMessage" />
// ...
computed: {
...mapState({
message: state => state.obj.message
})
},
methods: {
updateMessage (e) {
this.$store.commit('updateMessage', e.target.value)
}
}
// ...
mutations: {
updateMessage (state, message) {
state.obj.message = message
}
}
必須承認(rèn),這樣做比簡(jiǎn)單地使用“v-model + 局部狀態(tài)”要啰嗦得多,并且也損失了一些 v-model 中很有用的特性。另一個(gè)方法是使用帶有 setter 的雙向綁定計(jì)算屬性:
<input v-model="message" />
// ...
computed: {
message: {
get () {
return this.$store.state.obj.message
},
set (value) {
this.$store.commit('updateMessage', value)
}
}
}
vuex 嚴(yán)格模式
開啟嚴(yán)格模式,僅需在創(chuàng)建 store 的時(shí)候傳入 strict: true:
const store = new Vuex.Store({
// ...
strict: true,
// strict: process.env.NODE_ENV !== 'production' // 不要在發(fā)布環(huán)境下啟用嚴(yán)格模式!
});
在嚴(yán)格模式下,無論何時(shí)發(fā)生了狀態(tài)變更且不是由 mutation 函數(shù)引起的,將會(huì)拋出錯(cuò)誤。這能保證所有的狀態(tài)變更都能被調(diào)試工具跟蹤到。