How can I conditionally apply value to the data variable based on props, the ternary operator is generating error, I would like to refer to this code:
<template>
<div >
<img
:src="hamburgerUrl"
style="width: 25px; cursor: pointer; transform: translateY(-50%)"
alt="toggle menu button"
/>
</div>
</template>
<script>
export default {
name: "HamburgerMenu",
props: ["white"],
data: {
hamburgerUrl: this.white
? "/gfx/hamburger-white.png"
: "/gfx/hamburger-menu.png",
},
};
</script>
and I get the error saying :
TypeError
Cannot read property 'white' of undefined
I have tried to validate the props and set it to not required like so:
props: {
white: {
type: Boolean,
required: false,
default: false,
},
},
But it didn't help, what am I doing wrong? Thanks
CodePudding user response:
If you need a data
variable that depends of another variable, you must use a computed property.
You have to check about that on de official docs: Computed Properties
And instead of hamburguerUrl on data, you put it on the computed propert
<script>
export default {
name: "HamburgerMenu",
props: ["white"],
computed: {
hamburgerUrl() {
return this.white
? "/gfx/hamburger-white.png"
: "/gfx/hamburger-menu.png";
}
},
};
</script>
And that's all.