解決Vue 給mapState中定義的屬性賦值報錯的問題
1. 實踐環(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ù)時,給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
通過對比當(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中定義的屬性賦值報錯的問題的文章就介紹到這了,更多相關(guān)vue給mapState屬性賦值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue3+Element-plus項目自動導(dǎo)入報錯的解決方案
vue3出來一段時間了,element也更新了版本去兼容vue3,下面這篇文章主要給大家介紹了關(guān)于Vue3+Element-plus項目自動導(dǎo)入報錯的解決方案,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-07-07element多個table實現(xiàn)同步滾動的示例代碼
本文主要介紹了element多個table實現(xiàn)同步滾動,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09vue3+vite+SQL.js如何讀取db3文件數(shù)據(jù)
這篇文章主要介紹了vue3+vite+SQL.js如何讀取db3文件數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05window.onresize在vue中只能使用一次,自適應(yīng)resize報錯問題
這篇文章主要介紹了window.onresize在vue中只能使用一次,自適應(yīng)resize報錯問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10