【问题标题】:Why is my store not updating when I use a deep watch?为什么我使用深度手表时我的商店不更新?
【发布时间】:2019-10-22 00:24:36
【问题描述】:

当我更改文本字段的值时,我为此组件设置的深度观察器不会更新存储。我找不到正确更改存储对象(配置文件)键/值对的方法(组名:string

Profile.vue 元素

<v-text-field v-model="profileData.groupName" label="Group Name"></v-text-field>

Profile.vue JS

import { mapGetters, mapMutations } from "vuex";

export default {
  name: "Profile",
  created() {
    this.profileData = JSON.parse(JSON.stringify(this.getProfile()));
    console.log(this.profileData);
  },
  data() {
    return {};
  },
  methods: {
    ...mapGetters(["getProfile"]),
    ...mapMutations(["setProfile"])
  },
  watch: {
    profileData: {
      handler(value) {
        this.setProfile(value);
      },
      deep: true
    }
  }
};

build.jsstore.js 的模块):


const state = {
    profile: {
        "groupName": "Happy group",
        "groupNumber": "9999999999",
        "groupContact": "Bob Ross"
    }
};

const getters = {
    getProfile: (state) => state.profile,
};

const actions = { };

const mutations = { 
    setProfile: (state, profile) => (state.profile = profile)
};

export default {
    state,
    getters,
    actions,
    mutations,
}

我不确定为什么状态没有更新。有人知道吗?

感谢您的阅读

【问题讨论】:

  • (1) 分配一个对象不会复制它,所以pp 实际上是指您存储中的同一个对象(并且您应该在编辑时仍然看到 Vuex 突变警告)。 (2) 在pp 上尝试一个深度观察者,用新值调用setProfile

标签: javascript vue.js vuex store


【解决方案1】:

这是因为 Vue 允许你在非严格模式时直接修改 vuex 状态。如果启用严格模式,突变处理程序之外的任何突变都会引发错误。

export default {
  state,
  getters,
  actions,
  mutations,
  strict: true
}

Vuex 指南提到它here。你也可以只为开发启用它

strict: process.env.NODE_ENV !== 'production'

【讨论】:

  • 我添加了严格模式。即使我只映射 getter,它也不会限制我改变状态。
  • 直接更新状态是否会在控制台报错?
  • 直接更新状态后控制台没有报错。
  • 我设置错了。得到错误:Error: [vuex] do not mutate vuex store state outside mutation handlers.
  • 太好了,它可能不会限制您更新状态,但您应该会收到有关不正确突变的错误警告。
【解决方案2】:

不应该像您在此处所做的那样绑定状态变量v-model="profile.groupName"(实际上,您正在对 vuex 突变之外的道具进行突变,并且您可能会收到一些控制台警告)。

因此,您可以将 getProfile 值复制到局部变量(vue 的 data())并调度 action 以在需要时更新 profile 状态(根据处理程序或其他) .

【讨论】:

  • 我尝试编辑它以使用副本,但它不起作用。将其添加到原始帖子中。
  • 我尝试使用 JSON.parse(JSON.stringify(this.getProfile())) 并且它仍然将其解析为存储对象{__ob__: Observer} (i.imgur.com/FX5vOJV.png)
猜你喜欢
  • 1970-01-01
  • 2018-05-06
  • 2017-02-22
  • 2016-02-28
  • 2019-12-28
  • 2012-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多