我正在为 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
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
以及基本的手表功能:
watch: {
template: {
handler: function(){
this.save();
},
deep: true
}
}
Run Code Online (Sandbox Code Playgroud)
模板中变量的 isSelected 字段仅用于 UI 目的,我希望手表忽略该字段的更改,因为它们不会被保存。我不想为变量中的每个字段设置一个监视函数,而是在监视中执行以下操作:
ignore: "template.variables.isSelected"
Run Code Online (Sandbox Code Playgroud)
小智 1
您无法获取突变对象的旧值,因此我认为创建如下一些辅助数据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
}
}
});Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>Run Code Online (Sandbox Code Playgroud)