解決Vue 給mapState中定義的屬性賦值報(bào)錯(cuò)的問(wèn)題
1. 實(shí)踐環(huán)境
Vue 2.9.6
2. 問(wèn)題描述
<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方法名稱(chēng),并不是methods中定義的方法名稱(chēng),而是store中定義的方法
4. 解決方案2
通過(guò)對(duì)比當(dāng)前屬性值和store狀態(tài)值,然后根據(jù)比較結(jié)果,決定是否根據(jù)store狀態(tài)管理規(guī)則更新?tīng)顟B(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ò)的問(wèn)題的文章就介紹到這了,更多相關(guān)vue給mapState屬性賦值內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法2. html小技巧之td,div標(biāo)簽里內(nèi)容不換行3. nestjs實(shí)現(xiàn)圖形校驗(yàn)和單點(diǎn)登錄的示例代碼4. 以PHP代碼為實(shí)例詳解RabbitMQ消息隊(duì)列中間件的6種模式5. python實(shí)現(xiàn)自動(dòng)化辦公郵件合并功能6. python開(kāi)發(fā)飛機(jī)大戰(zhàn)游戲7. laravel ajax curd 搜索登錄判斷功能的實(shí)現(xiàn)8. css進(jìn)階學(xué)習(xí) 選擇符9. Echarts通過(guò)dataset數(shù)據(jù)集實(shí)現(xiàn)創(chuàng)建單軸散點(diǎn)圖10. Python 如何將integer轉(zhuǎn)化為羅馬數(shù)(3999以?xún)?nèi))
