0
How can i make nested object property access data from its parent object's property in vue.js? [Solved]
I tried but i cant get it... data:{ changeClass: true, box:{ coloredBox: this.changeClass, }, } coloredBox is the class in css but when i inspect this element , there isn't this class. why?
14 Respostas
+ 3
Try this
data: {
changeClass: true,
},
computed: {
coloredBox() {
return this.changeClass;
}
}
// OR
data: {
changeClass: true,
box: {
coloredBox: undefined,
}
},
mounted() {
this.box.coloredBox = this.changeClass;
}
+ 3
What if i dont want to use computed or watcher.. i am just trying to understand how a nested object can access data from its parent object??
+ 2
Are you talking about CSS classes or ES 6 classes?
I feel like I am missing some context here. Can you post the full code here or at least the complete Vue component?
+ 2
i was talking about css class.
wait I'll just save the code at SoloLearn.
+ 2
That can be the solution, yes, thanks a lot Ore.
But i wish there was some easier and faster way to access the data from parent object since i just started learning Vue.
+ 1
Ore here's the code. I made some changes to help understand better.
https://code.sololearn.com/WZ4hEAu7216C/?ref=app
+ 1
Have you tried using a watcher instead
watch: {
validation(val) {
this.greenBlock.green = val;
}
}
+ 1
I don't think it is possible.
+ 1
Ore Really? You sure?
+ 1
Computed properties or watchers seem to be the right way to approach this problem. If you do not care about reactivity, you can also set it manually in the mounted() hook.
+ 1
There is no reason to have your css classes as data variables. Data should only have the variables necessary to reflect the internal state of the component.
No redundancy needed. in that case use computed.
Just bind the classes direct on the html element instead:
<div :class="{coloredBox: changeClass}" />
+ 1
John Doe Got it. I was going through the Vue official docs and i saw it there to use separate object for css properties and not to use it inline. Also if i wanted to change values of properties dynamically , a separate css object seems better idea than inline , isn't it?
+ 1
im interested in this topic also.. Any other ideas? seems like when i console log this on a data object value I can see all the data properties and methods available from vue. so why is the property undefined when i use this.myProperty?
0
Ore yes i get it goes in computed object.. but wasn't coloredBox a class?