国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

解決Vue 給mapState中定義的屬性賦值報錯的問題

瀏覽:7日期:2023-01-11 17:04:57

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ù)時,給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)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Vue
相關(guān)文章:
主站蜘蛛池模板: 永和县| 怀化市| 杭锦后旗| 土默特左旗| 大洼县| 泸西县| 天津市| 疏附县| 巧家县| 天等县| 泾川县| 铁力市| 普洱| 丹东市| 西乡县| 望奎县| 麦盖提县| 宁海县| 苏州市| 灵石县| 甘洛县| 大足县| 丰镇市| 延吉市| 安福县| 天门市| 利川市| 娄烦县| 城口县| 安图县| 湖北省| 洞头县| 拉萨市| 南川市| 丰镇市| 吉安市| 大余县| 汕尾市| 凯里市| 高雄市| 手游|