Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
10
rated 0 times [  11] [ 1]  / answers: 1 / hits: 17257  / 7 Years ago, fri, march 17, 2017, 12:00:00

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


More From » node.js

 Answers
13

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>

[#58496] Thursday, March 16, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
havenbilliec

Total Points: 324
Total Questions: 106
Total Answers: 94

Location: Pitcairn Islands
Member since Fri, Oct 15, 2021
3 Years ago
;