DAY29 | 跟 Vue.js 認識的30天 - Vue 套餐之圖書館 Vuex (下)

紀錄一下,其他 Vuex 的進階觀念(主要以我看得懂得為主 :sweat_smile: )!

嚴格模式

在 Vuex 中開啟嚴格模式,可以確保所有 state 值的改變都是由 mutations 中的函數所造成的,如果不是將會拋出錯誤。
但是必須注意不能再生產模式(production)中開啟嚴格模式!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const store = new Vuex.Store({
state: {
//...
},
getters: {
//...
},
mutations: {
//...
},
actions: {
//...
},
// 開啟嚴格模式
strict: process.env.NODE_ENV !== 'production'
})

表單處理

使用 Vue 最好用的一個功能就是表單雙向綁定 v-model ,但是如果把資料綁在 Vuex 中那要如何實現雙向綁定?

方法一:捨棄 v-model

讓元素的透過 v-bind:value = 'computed值' 綁定值,透過 v-on:input = '事件名' 綁定事件。
透過 v-on:input = '事件名' 去提交 store.commit(type, payload) 改變 Vuex state 的值。

1
2
3
<div id="vm">
<input type="text" :value="msg" @input="updateMsg">
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const store = new Vuex.Store({
state: {
msg: '我是一段訊息'
},
mutations: {
updateMsg(state, payload){
state.msg = payload
},
},
})

const vm = new Vue({
el: '#vm',
store,
computed:{
msg(){
return this.$store.state.msg
},
},
methods: {
updateMsg(e) {
this.$store.commit('updateMsg', e.target.value)
},
}
})

方法二:使用 computed 中的 getter 及 setter

1
2
3
<div id="vm">
<input type="text" :value="msg" @input="updateMsg">
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const store = new Vuex.Store({
state: {
msg: '我是透過v-model改變訊息'
},
mutations: {
updateMsg(state, payload){
state.msg = payload
},
},
})

const vm = new Vue({
el: '#vm',
store,
computed:{
msg: {
get() {
// 取得返回值
return this.$store.state.msg
},
set(newVal) {
// 如果賦予 msg 新值時,就執行 setter
this.$store.commit('updateMsg', newVal)
}
},
}
})

有關於 computed 中 getter 跟 setter 的使用方法可以參考:DAY03 | 跟 Vue.js 認識的30天 - Vue 的資料計算(computed)

Demo

See the Pen DAY29 | 跟 Vue.js 認識的30天 - Vue 套餐之圖書館 Vuex (下) by Celeste6666 (@celeste6666) on CodePen.

參考資料

严格模式

表单处理