【问题标题】:how to call function in component after change value in store?更改存储中的值后如何调用组件中的函数?
【发布时间】:2018-07-14 19:00:08
【问题描述】:

我有一个包含一些值和两个组件的商店。 当我需要在 red value 更改后调用函数时,第一个组件是它的范围滑块,第二个组件是它的组件。

在第一个组件中,我更改滑块值并将其添加到 vuex 存储中。

state: {
    value: 0,
      rgbColors: {
        red: 0
      }
  },

我怎么知道我需要使用store.subscribe.watch.rgbColors.redstore.watch.rgbColors.red,它是否正确?

如果正确的话,改变值后如何调用一些函数?

【问题讨论】:

    标签: javascript vue.js vuejs2 vuex


    【解决方案1】:

    store.subscribe 订阅 mutators。 Ala:如果您调用this.$store.commit('myMutator', payload),您的订阅者函数将使用myMutatorpayload 调用。这不是你想要的。

    store.watch 将监视您定义的状态的某些部分,但它的主要缺点是您确实需要手动取消监视。我相信你会这样使用它:

    const unWatchFn = store.watch(
      (state) => state.rgbColors.red,
      (newRed) => {
        console.log(newRed)
      }
    );
    
    // And sometime later
    unWatchFn()
    

    您通常不想在 Vue 中使用实际的观察者,因为通过计算属性计算事物会自动使计算变量保持最新。如果您需要使用观察程序,请在实际组件上使用它们,以便它们自动被删除,并且不会导致内存泄漏或奇怪的错误。无论哪种情况,您都需要在 store 模块中创建一个 getter。然后在这个 getter 上的组件中创建一个计算属性或一个观察者。

    // store.js
    export default {
      state: {
        rgbColors: {
          red: 0,
          green: 0,
          blue: 0
        }
      },
    
      getters: {
        color(state) {
          return state.rgbColors;
        }
      },
    
      mutations: {
        setColor(state, { red, green, blue }) {
          state.rgbColors.red = red;
          state.rgbColors.green = green;
          state.rgbColors.blue = blue;
        }
      }
    };
    
    // SomeComponent.vue
    <script>
    import { mapGetters } from "vuex";
    
    export default {
      name: "App",
    
      computed: {
        ...mapGetters(["color"]),
    
        styling() {
          const { red, green, blue } = this.color;
    
          return {
            "background-color": `rgb(${red}, ${green}, ${blue})`
          };
        }
      },
    
      watch: {
        color: {
          deep: true,
          handler(newColor) {
            console.log("Oh, look, a new color!", newColor);
          }
        }
      },
    
      methods: {
        setColor(red, green, blue) {
          this.$store.commit("setColor", {
            red,
            green,
            blue
          });
        }
      }
    };
    </script>
    

    【讨论】:

    • 你能@Sumurai8 解释一下吗` ...mapGetters(["color"]),`
    • @DarckBlezzer mapGetters 来自 vuex。它的工作原理与color() { return this.$store.getters.color; } 相同。有关更多信息,请参阅the documentation...mapGetters 之前的mapGetters 解构了从mapGetters 返回的对象,因此我们可以在computed 对象中使用来自mapGetters 调用的键和值。
    猜你喜欢
    • 2020-10-26
    • 1970-01-01
    • 2019-10-29
    • 1970-01-01
    • 2021-01-29
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    相关资源
    最近更新 更多