猿问

Vue 代码覆盖 Vuex 存储中的嵌套属性

我已经设置了一个 Vuex 商店,以便在不同的组件之间共享状态。一位同事不小心在 Vuex 存储上设置了一个新属性,而没有分派动作或提交突变,但没有崩溃,应用程序继续运行。有没有办法防止这种情况发生?


这是商店的结构(简化):


import Vue from 'vue';

import Vuex from 'vuex';


Vue.use(Vuex);


const store = new Vuex.Store({

  state: {

    options: {},

  },

  actions: {

    setAttributes (context, payload) {

        context.commit('setAttributes', payload);

    },

    setPrice (context, payload) {

        context.commit('setPrice', payload);

    }

  },

  mutations: {

    setAttributes (state, payload) {

      state.options.width = payload.width;

      state.options.height = payload.height;

    },

    setPrice (state, payload) {

        state.options.price = payload.price;

      },

  },

  getters: {

    options: state => {

      return state.options

    }

  }

});

这是 Vue 实例的结构:


import Vue from 'vue';

import { mapGetters } from 'vuex';

import { store } from './store/store';


new Vue({

    el: '#app',

    store,

    computed: {

        ...mapGetters([

            'options',

        ])

    },

    mounted() {

        this.$store.dispatch('setAttributes', {

            width: 100,

            height: 80,

        });

    } 

  });

为了改变价格,我会做这样的事情:


this.$store.dispatch('setPrice', {

    price: 800,

});

但我们发现这也是可能的:


this.options.price = 800;

有没有办法阻止它,或者我们应该避免在共享状态下使用嵌套对象?


FFIVE
浏览 237回答 1
1回答

30秒到达战场

由于Phil在评论中给出了答案,我将在此处引用并接受答案:在你的商店中启用严格模式 ~ vuex.vuejs.org/guide/strict.html
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答