vue js使用单个处理程序监视多个属性

vue.js Vue.js

西门JinJin

2020-03-12

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

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

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

PS:我正在使用vue 1.x

第1361篇《vue js使用单个处理程序监视多个属性》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
Tony宝儿 2020.03.13

首先,您的定义可以简化。doSomething似乎不是Vue上的一种方法,所以您的手表可能只是

watch:{
    propa: doSomething,
    propb: doSomething
}

其次,有时重要的是要记住Vue定义对象只是普通的javascript对象。它们可以***纵。

如果您想观看数据对象中的每个属性,则可以执行以下操作

function doSomething(after, before){
  console.log(after,before);
}

function buildWatch(def){
  if (!def.watch)
    def.watch = {};
  for (let prop of Object.keys(def.data))
    def.watch[prop] = doSomething;
  return def;
}

let vueDefinition = {
  data:{
    propa: "testing",
    propb: "testing2",
    propc: "testing3"
  }
}

export default buildWatch(vueDefinition)

如果您只想看一些定义的属性列表:

// First argument is the definition, the rest are property names
function buildWatch(def){
  if (!def.watch)
    def.watch = {};
  const properties = Array.prototype.slice.call(arguments,1); 
  for (let prop of properties)
    def.watch[prop] = doSomething;
  return def;
}

export default buildWatch(vueDefinition, "propa", "propb")

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android