[Vuex] 中-嵌套对象的重置与-响应式的注意事项

129 阅读1分钟

function getDefaultState() {
  const state = {
    loading: {
      create: false,
      list: false,
      view: false,
    },
    form: {
      // details form
      name: '',
      email: '',
      password: '',
      confirmPassword: '',

      status: '',

    },
  };
  return state;
}

const user = {
  state: getDefaultState(),
  mutations: {
      RESET_STATE: (state) => {
        // TODO http://eslint.org/docs/rules/no-param-reassign  Assignment to function parameter 'state'
        // TODO what is best practice for reseting vuex state

        // [Warning]: 下面这种做法是错的,违反 Vue 响应式原则。
        // 参见:https://forum.vuejs.org/t/replacing-state-object-not-updating-getter-in-vuex/10149/8
        // state = getDefaultState();

        // 使用如下代码 重置 state,对每个 key 单独赋值
        const defaultState = getDefaultState();
        Object.keys(defaultState).forEach((key) => {
          state[key] = defaultState[key];
        });
      },

  }
}