I'm using Vue.js and when I try to access a variable from data inside a computed property, it returns undefined
.
Here's the code:
<script>
export default {
name: 'app',
data: () => {
return {
lang: 'sp'
}
},
computed: {
langEn: () => this.lang === 'en',
langSp: () => this.lang === 'sp'
}
}
</script>
This is in a NPM project. And inside a .vue
file. Maybe it behaves differently when used like this?
Thanks for the help
You can even watch other computed props, as well as reactive data in data() ! Computed properties are required to be pure functions. This means that they return a new value, but aren't allowed to change anything, and they must be synchronous.
In Vue. js, computed properties enable you to create a property that can be used to modify, manipulate, and display data within your components in a readable and efficient manner. You can use computed properties to calculate and display values based on a value or set of values in the data model.
This is a very common "gotcha".
Do not use a fat arrow when defining your computed.
When you use a fat arrow to define your computed, methods, or data, you capture this
lexically and it will point to the containing scope (which is often window
or undefined) and not your Vue.
<script>
export default {
name: 'app',
data() {
return {
lang: 'sp'
}
},
computed: {
langEn(){return this.lang === 'en'},
langSp(){return this.lang === 'sp'}
}
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With