首页 > 解决方案 > 忽略 VueJs 深入观察中的一些属性

问题描述

我正在为 vue 应用程序开发自动保存功能,每次对 vue 应用程序数据进行更改时,它都会向 api 发送数据。使用 vue watch 时是否可以忽略对象的某些属性?该对象有多个值,我想监视以自动保存,只有 1 或 2 个会被忽略,因此为我想要的所有属性设置监视函数似乎没有意义,而只是忽略 1我不。

这是数据的基本结构:

data:{
  template: {
    name: "Template",
    id: 1,
    variables: [
      {
        name: "v1",
        color: "#fff",
        group: 1,
        isSelected: true
      },
      {
        name: "v2",
        color: "#fff",
        group: 3,
        isSelected: false
      }
    ]
  }
}

和基本的手表功能:

watch: {
  template: {
    handler: function(){
      this.save();
    },
    deep: true
  }
}

模板中变量的 isSelected 字段仅用于 UI 用途,我希望手表忽略该字段更改,因为它们没有被保存。我不想为变量中的每个字段设置监视函数,而是在监视中执行以下操作:

ignore: "template.variables.isSelected"

标签: javascriptvue.js

解决方案


您无法获得突变对象的旧值,因此我认为创建如下的一些辅助数据temp(save old data)将帮助您解决问题。然后检查新旧数据....

var app = new Vue({
el: "#app",
data:{
  a: 1,
  template: {
    name: "Template",
    id: 1,
    variables: [
      {
        name: "v1",
        color: "#fff",
        group: 1,
        isSelected: true
      },
      {
        name: "v2",
        color: "#fff",
        group: 3,
        isSelected: false
      }
    ]
  },
  temp: {}
},
mounted: function() {
// this.template.variables[0].isSelected = false;
 this.temp = JSON.parse(JSON.stringify(this.template));
 this.$set(this.template.variables[0],"isSelected", 222);
 
},
watch : {
 template: {
   handler: function(changeVal) {
     var flag = true;
     for(var i in changeVal.variables) {
       if(changeVal.variables[i].isSelected != this.temp.variables[i].isSelected) {
         flag = false;
       }
     }
     this.temp = JSON.parse(JSON.stringify(this.template)); // assign changed data as old data again for next process
     if(flag) console.log("saveData");// this.save();
     else console.log("notsave");
   },
   deep: true
 }
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>


推荐阅读