[英]Checkbox state does not change on click
在我的Model.vue組件中(在Nuxt.js和Vuetifyjs應用程序中),我有這段代碼:
<v-checkbox v-model="selected"></v-model>
在該組件的腳本部分,我有:
computed: {
selected: {
get() {
return this.$store.state.selected
},
set(value) {
this.$store.commit('UPDATE_SELECTED', value)
}
},
},
在商店中,我有這個:
mutations: {
UPDATE_SELECTED: (state, value) => {
state.selected.push(value)
}
}
並且此存儲的狀態包含選定的條目,如下所示:
state: {
selected: []
}
AFAIK,我遵照了文檔說明 ,但是當我單擊v-checkbox
組件時,它不會選中/取消選中。 怎么了?
發生問題是因為您正在使用一個數組來建模名為selected
的布爾狀態屬性。 因此,根據您的代碼,在突變方面,每個突變都將新布爾值推入名為selected
的數組的最新位置。
同樣,在get端,計算屬性的get()
函數將整個數組作為要顯示的屬性返回,從而導致客戶端未選中的復選框。
因此,假設您需要處理多個復選框,為了使當前復選框能夠正常工作,您可以將其編寫如下:
Vuex商店
let store = new Vuex.Store({
state: {
selected: []
},
mutations: {
UPDATE_SELECTED: (state, value) => {
//mutating the 0th array position of the selected property
state.selected[0] = value
}
}
})
計算財產
computed: {
selected: {
get() {
//getting the 0-index element of the array, assuming this checkbox is the 0th
return this.$store.state.selected[0]
},
set(value) {
this.$store.commit('UPDATE_SELECTED', value)
}
}
}
在這里,您可以找到一個工作的小提琴 。
另外,如果您只需要在應用程序狀態中處理一個復選框,就可以將state.selected
屬性建模為布爾值就足夠了。 我的意思是,按如下所示修改Vuex狀態就足夠了:
state: {
selected: true //or false if you expect unchecked checkbox as default
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.