Vue 給mapState中定義的屬性賦值報錯的解決方案


Vue mapState中定義的屬性賦值報錯的解決方案

by:授客 QQ1033553122

1.   實踐環境

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>

 

如上,我們希望在執行increaseCount函數時,給mapstate函數中映射定義的this.count賦值,給該值增加1,結果,提示

[Vue warn]: Computed property "count" was assigned to but it has no setter.

 

3.   解決方案1

如下,把屬性“移出mapState”,然后為屬性新增get,set方法,分別用於獲取值和改變值(按store狀態管理規定的方式)

 

<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

通過對比當前屬性值和store狀態值,然后根據比較結果,決定是否根據store狀態管理規則更新狀態值。

<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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM