教女朋友|表弟系列:问题解决-vue的data中obj.a的值依赖于data中b,c的值如何解决?
问题场景:
export default {
data() {
return {
obj: {
a: false
},
b: true,
c: true
}
}
}
代码如上,希望实现这样的效果:如果b、c都为true,则obj.a为true。
解决方案:
目前我所提供的解决方案是computed+watch,不过感觉不是最优解,不知道广大麻友们有没有更好的思路,非常感谢!
方案一:
export default {
data() {
return {
obj: {
a: false
},
b: true,
c: true
}
},
computed: {
flag() {
return this.b && this.c
}
},
watch: {
flag(newval) {
this.obj.a = newval;
}
}
}
另外下面这样是不支持的,因为data先于computed渲染。
export default {
data() {
return {
obj: {
a: this.flag
},
b: true,
c: true
}
},
computed: {
flag() {
return this.b && this.c
}
}
}
另外这样也是不行的,因为渲染data的obj.a的值时,this.b和this.c还访问不到,也建立不了关联,不过computed钩子声明的数据能访问到,可惜值是undefined,只能访问到声明:
export default {
data() {
return {
obj: {
a: this.b && this.c
},
b: true,
c: true
}
}
}