javascript - 忽略 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"
解决方案
您无法获得突变对象的旧值,因此我认为创建如下的一些辅助数据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>
推荐阅读
- amazon-web-services - Aws Cognito 托管 UI。从触发器返回错误消息
- jenkins - 我怎样才能有不同的工作配置和其中一个运行
- camunda - Camunda Modeler 没有高级模式按钮
- flutter - 如何创建具有内阴影和渐变填充的卡片
- reactjs - 对于 React 项目,@emotion/react 比 @emotion/css 有什么好处?
- python - 尝试导入时没有名为“PyPDF2”的模块
- apache - Htaccess 将子文件夹重写为子域
- python - 在 gcloud -django 上上传图片时没有名为“config”的模块
- sapui5 - 预期为 '}' 而在表达式中看到 '='
- java - 使用 Canvas 正确绘制点