vue js使用单个处理程序观看多个属性 [英] vue js watch multiple properties with single handler

查看:70
本文介绍了vue js使用单个处理程序观看多个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我不得不看一些属性.如果它们每个都发生变化,我必须调用相同的函数:

Currently I have to watch a few properties. And if each of them changes, I have to invoke the same function:

export default{
  // ...... rest of code 
  watch: {
    propa: function(after,before) {
      doSomething(after,before);
    },
    propb: function(after,before) {
      doSomething(after,before);
    }
    // ... so on
  }
}

因此,我不得不多次编写相同的代码. 是否可以简单地监视所有属性并调用其更改处理程序,而不必多次编写相同的代码?

So I am having to write the same code multiple times above. Is it possible to simply have all properties being watched and invoke their change handler without having to write same code multiple times?

PS:我正在使用vue 1.x

PS: I am using vue 1.x

推荐答案

更新时间:2020年4月

对于使用Vue 3的用户,watch API可以接受多个来源

For people who are using Vue 3, the watch API can accept multiple sources

import { watch, ref } from 'vue';

export default {
  setup(() => {
    const a = ref(1), b = ref('hello');

    watch([a, b], ([newA, newB], [prevA, prevB]) => {
      // do whatever you want
    });
  });
};


Vue 2的原始答案

没有官方的方法可以解决您的问题(请参见).但是您可以将计算属性用作技巧:

there is no official way to solve your question(see this). but you can use the computed property as a trick:

export default {
  // ...
  computed: {
    propertyAAndPropertyB() {
      return `${this.propertyA}|${this.propertyB}`;
    },
  },
  watch: {
    propertyAAndPropertyB(newVal, oldVal) {
      const [oldPropertyA, oldProvertyB] = oldVal.split('|');
      const [newPropertyA, newProvertyB] = newVal.split('|');
      // doSomething
    },
  },
}

如果您只想做某事,而不关心新的/旧的值. 忽略两行

if you just want to do something and don't care about what's new/old values. ignore two lines

const [oldPropertyA, oldProvertyB] = oldVal.split('|');
const [newPropertyA, newProvertyB] = newVal.split('|');

这篇关于vue js使用单个处理程序观看多个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆