代码之家  ›  专栏  ›  技术社区  ›  Peter V. Mørch

在没有实际更改的情况下调用了vue监视处理程序

  •  0
  • Peter V. Mørch  · 技术社区  · 7 年前

    在这个 codepen 有一个可以用“incr”链接递增的计数器。

    我现在有了一个计算财产和一块手表:

    computed: {
      test() {
        let unused = this.counter;
        return [42];
      }
    },
    watch: {
      test(val, old) {
    
        // Should I avoid firing when nothing actually changed
        // by implementiong my own poor-man's change detection?
        //
        // if (JSON.stringify(newVal) == JSON.stringify(oldVal))
        //   return;
    
        console.log(
          'test changed',
          val,
          old
        );
      }
    }
    

    这也许是一个人为的例子,但实际上这是一个实际数据被缩减的计算(在vuex getter中),而且大多数情况下,即使某些数据发生了变化,缩减后的数据也不会发生变化。

    编辑以添加更多详细信息 :vuex中的数据 store 是标准化的。我们也在使用 vue-grid-layout 它期待着 layout a中的属性 certain 非规范化格式。所以我们有一个 gridLayout 执行vuex的getter->vue网格布局转换。观察这个gridLayout getter,即使结果gridLayout没有实际更改,但其他细节会更改,例如名称和vuex存储中与vue grid layout对象键无关的其他细节。

    在上面的例子中,当 this.counter 变化,手表开着 test 也会开火,尽管 newVal oldVal 都是“一样的”。他们不是 == 或 === 请注意,但“和”中的“一样” JSON.stringify(newVal) == JSON.stringify(oldVal) .

    有没有办法让我 watch 只有在有实际变化时才开火?实际比较 JSON.stringify() 对我来说似乎效率很低,但我担心随着我的项目的增长,性能问题,因为我的手表可以做昂贵的操作,我想确保我没有错过什么。

    0 回复  |  直到 7 年前
        1
  •  0
  •   Tim Wickstrom    7 年前

    在您的例子中,被动依赖是 this.counter

    通过调用方法而不是计算属性,可以获得相同的结果。

    只需更改组件体系结构:

    data () {
      return: {
        counter: 0,
        obj: {},
        output: null
      }
    },
    watch: {
      counter(val, old) {
        // Alternatively you could remove your method and do something here if it is small
        this.test(val);
      },
      // Deep watcher
      obj: {
        handler: function (val, oldVal) {
            console.log(val);
            console.log(oldVal);
            this.test(val);
        },
        deep: true
    },
      }
    },
    methods: {
      test() {
        let unused = this.counter;
        if (something changed)
          this.output = [42];
        }
      }
    }
    

    现在在模板(或其他计算属性)中 output

    阅读更多: https://vuejs.org/v2/guide/computed.html#Computed-Caching-vs-Methods

    推荐文章