如何在不触发反应性的情况下计算Vuex状态差异

时间:2019-02-28 12:33:37

标签: javascript vue.js vuex

我有一些组件列表,这些组件在单击后会更改Vuex状态。 而且我想呈现两个Vuex状态值之间的区别:单击处理程序派发的动作前后。

可能是这样的:

<template>
<ul>
  <li v-for="item of items" @click="clickItem">{{difference}}</li>
</ul>
</template>
<script>
    export default {
        methods: {
              difference() {
                  let oldValue = this.$store.getters.getValue();
                  this.$store.dispatch(SOME_ACTION);
                  let newValue = this.$store.getters.getValue();
                  this.$store.dispatch(UNDO_SOME_CATION);
                  return newValue-oldValue;
              }
              clickItem() {
                  this.$store.dispatch(SOME_ACTION);
              }
        }
    }
</script>

但是问题在于此代码会产生无限的渲染循环,因为动作调度会更改Vuex存储和Vuex反应性 进而触发应用组件的重新渲染。

是否有可能比分派操作禁用Vuex反应性,获取新值,比分派撤消操作并启用反应性?如果可以,那么可以解决我的问题。

1 个答案:

答案 0 :(得分:0)

这未经测试,但是我的想法是让difference从IIFE(立即调用的函数表达式)返回其功能,然后添加一个标志以标识是否已分派。

const difference = (function() {
  let dispatched;

  return function() {
    if (dispatched) {
      dispatched = false;
      return;
    }

    let oldValue = this.$store.getters.getValue();
    this.$store.dispatch(SOME_ACTION);
    dispatched = true;

    let newValue = this.$store.getters.getValue();
    this.$store.dispatch(UNDO_SOME_CATION);
    return newValue-oldValue;
  }
})()
相关问题