您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)Vue使用mapState時(shí)報(bào)錯(cuò)的解決方法,文章內(nèi)容質(zhì)量較高,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
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>
以上就是Vue使用mapState時(shí)報(bào)錯(cuò)的解決方法,看完之后是否有所收獲呢?如果想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊,感謝各位的閱讀。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。