Vue将值计算为数据属性值



简化示例组件代码:

<template>
<section>
<div>{{ z }}</div>
<div>{{ compZ }}</div>
<div>{{ x }}</div>
</section>
</template>
<script>
export default {
name: "example",
data: () => ({
z: false,
x: [{ visible: null }]
}),
mounted() {
this.x[0].visible = this.compZ;
setTimeout(() => (this.z = true), 1e3);
},
computed: {
compZ() {
return this.z;
}
}
};
</script>

之后的第二个结果是:

true
true
[ { "visible": false } ]

compZ更改时,我需要更改x[n].visible。关于如何干净地保持反应性,有什么想法吗?这是必需的,因为我有22个潜在的步骤,这些步骤是可见的,取决于初始化后可能更改的某些标志。

您可以为z添加观察程序。

watch: {
z: function (newValue, oldValue) {
// here you can change x.y
}
},

找到了一个变通方法,但我认为它很难看:

<template>
<section>
<div>{{ refFlag1 }}</div>
<div>{{ compRefFlag1 }}</div>
<div>{{ x }}</div>
</section>
</template>
<script>
export default {
name: "example",
data: () => ({
refFlag1: false,
refFlag2: false,
x: [{ visible: null, visibleFunc: "that.compRefFlag1" }]
}),
watch: {
allRelevatFlags: function () {
setTimeout(() => this.updateVisible());
}
},
mounted() {
this.x[0].visible = this.compRefFlag1;
setTimeout(() => (this.refFlag1 = true), 1e3);
},
methods: {
updateVisible() {
// eslint-disable-next-line no-unused-vars
let that = this; // eval doesn't see 'this' scope
this.x.forEach(step => (step.visible = eval(step.visibleFunc)));
}
},
computed: {
allRelevatFlags() {
return `${this.compRefFlag1}${this.compRefFlag2}`;
},
compRefFlag1() {
return this.refFlag1;
},
compRefFlag2() {
return this.refFlag2;
}
}
};
</script>

注意任何相关标志的变化,然后使用JSeval()重新设置visible标志。

一定有更好的方法。。。

最新更新