解決Vue 給mapState中定義的屬性賦值報(bào)錯(cuò)的問題
1. 實(shí)踐環(huán)境
Vue 2.9.6
2. 問題描述
<script>
import { mapState } from 'vuex';
export default {
name: "displayCount",
computed: {
...mapState({
...略
count: state => state.a.count
})
},
methods: {
increaseCount () {
this.count = this.count + 1
}
}
};
</script>
<style>
</style>
如上,我們希望在執(zhí)行increaseCount函數(shù)時(shí),給mapstate函數(shù)中映射定義的this.count賦值,給該值增加1,結(jié)果,提示
[Vue warn]: Computed property "count" was assigned to but it has no setter.
3. 解決方案1
如下,把屬性“移出mapState”,然后為屬性新增get,set方法,分別用于獲取值和改變值(按store狀態(tài)管理規(guī)定的方式)
<script>
import { mapState } from 'vuex';
export default {
name: "displayCount",
computed: {
...mapState({
...略
}),
count: {
get() {
return this.$store.state.a.count;
},
set(val) {
this.$store.commit("increaseCount", val);
}
}
},
methods: {
increaseCount () {
this.count = this.count + 1
}
}
};
</script>
注意:this.$store.commit("increaseCount", val);中的increaseCount方法名稱,并不是methods中定義的方法名稱,而是store中定義的方法
4. 解決方案2
通過對(duì)比當(dāng)前屬性值和store狀態(tài)值,然后根據(jù)比較結(jié)果,決定是否根據(jù)store狀態(tài)管理規(guī)則更新狀態(tài)值。
<script>
import { mapState } from 'vuex';
export default {
name: "displayCount",
computed: {
...mapState({
count: state => state.a.count
})
},
methods: {
increaseCount () {
if (this.count == this.$store.state.a.count) {
this.$store.commit("increaseCount", this.count+1);
}
}
}
};
</script>
總結(jié)
到此這篇關(guān)于解決Vue 給mapState中定義的屬性賦值報(bào)錯(cuò)的問題的文章就介紹到這了,更多相關(guān)vue給mapState屬性賦值內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用elementUI table展開行內(nèi)嵌套table問題
這篇文章主要介紹了使用elementUI table展開行內(nèi)嵌套table問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04
Vue + iView實(shí)現(xiàn)Excel上傳功能的完整代碼
前一段時(shí)間項(xiàng)目經(jīng)歷了前端上傳文件的過程,首先進(jìn)入頁面會(huì)展示默認(rèn)的樣子,選中要上傳的excel文件,本文通過實(shí)例圖文相結(jié)合給大家介紹的非常詳細(xì),需要的朋友參考下吧2021-06-06
Vue中使用?Aplayer?和?Metingjs?添加音樂插件的方式
這篇文章主要介紹了Vue中使用?Aplayer?和?Metingjs?添加音樂插件,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-08-08
ES6 Proxy實(shí)現(xiàn)Vue的變化檢測問題
Vue3.0將采用ES6 Proxy的形式重新實(shí)現(xiàn)Vue的變化檢測,在官方還沒給出新方法之前,我們先實(shí)現(xiàn)一個(gè)基于Proxy的變化檢測。感興趣的朋友跟隨小編一起看看吧2019-06-06
vue項(xiàng)目中實(shí)現(xiàn)緩存的最佳方案詳解
這篇文章主要給大家介紹了關(guān)于vue項(xiàng)目中實(shí)現(xiàn)緩存的最佳方案,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用vue具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
vscode下vue項(xiàng)目中eslint的使用方法
這篇文章主要給大家介紹了關(guān)于vscode下vue項(xiàng)目中eslint的使用方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01

