vuejs/vuex 中的监视和突变

Watch and mutation in vuejs/vuex

所以我设法从 state 获得了 watch 一个元素,但我还想从 state 更新一个元素。

这是我尝试过的方法,但无法正常工作:

<template>
  <input :style="styleForX" ... />
</template>


// script in template file :: isXActive returns focus input = true/false
 watch: {
  isXActive: (isXActive) => {
    console.log(123);
    this.$store.commit("SET_STYLE_FOR_X", isXActive);
  },
},
computed: {
  ...mapGetters([
    "styleForX",
]);


// state.js
export default state = {styleForX: ""}

// getters.js
styleForX: (state) => {
  return state.styleForX;
},

// action.js
SET_STYLE_FOR_X({commit}, isXActive) {
  const style = isXActive? {backgroundColor: "white", zIndex: "51"} : "";
  commit("SET_STYLE_FOR_X", style);
},


// mutation.js
SET_STYLE_FOR_X(state, styleForX) {
  state.styleForX= styleForX;
}

每个js文件都有export default语句。 知道我应该如何让它工作吗?

  1. 更新:

将代码更改为:

 watch: {
  isXActive: () => {
    this.$store.commit("SET_STYLE_FOR_X", {backgroundColor: "white", zIndex: "51"});
  },

但还是不行。 我得到 this 作为 undefined,所以我得到这个错误:

Error in callback for watcher "isXActive": "TypeError: Cannot read property '$store' of undefined" found in ...
  1. 更新 - 我将其更改为这个并且有效。但是如果有人知道如何使第一个版本工作,请发表评论。谢谢!
created() {
  this.$store.watch(
    () => this.$store.state.isXActive,
    () => {
      this.$store.commit("SET_STYLE_FOR_X", {backgroundColor: "white", zIndex: "51"});
    }
  );
}
  1. 更新 - 因为样式没有在聚焦时移除,所以我再次将其更改为:
created() {
  this.$store.watch(
    () => this.$store.state.isXActive,
    () => {
      this.$store.dispatch("SET_STYLE_FOR_X", isXActive);
    }
  );
}

// action.js
SET_STYLE_FOR_X({commit}, isXActive) {
  const style = isXActive? {backgroundColor: "white", zIndex: "51"} : "";
  commit("SET_STYLE_FOR_X", style);
},

  1. 更新 - 最终结果
 watch: {
  isXActive() {
    this.$store.commit("SET_STYLE_FOR_X", this.$store.state.isXActive);
  },

谢谢eli chen !!

您的代码无效。观察者中的 isXActive 布尔类型 (就像你在上面的评论中所说的那样)并且商店中的 styleForXstyle 对象类型 为输入设置样式。现在,当 watcher 被触发时,您将布尔类型发送到突变,突变将 styleForX 设置为布尔类型。

例如,您应该发送样式字符串而不是布尔值

watch: {
  isXActive: function() {
    this.$store.commit("SET_STYLE_FOR_X", {backgroundColor: "white", zIndex: "51"});
  }
}

对象样式类型的示例是 { color: 'red' }。这只是 js 对象,请在此处查看更多信息 https://vuejs.org/v2/guide/class-and-style.html#Binding-Inline-Styles

在您的手表处理程序中,当您似乎打算调用 this.$store.dispatch() 时,您正在调用 this.$store.commitcommit 运行突变。 dispatch 运行一个动作。您从布尔值计算样式的代码在操作中,因此您应该使用 dispatch.

也就是说,没有理由在此处使用操作,因为您没有任何异步代码。只需将样式字符串的逻辑放在突变中而不是动作中。