How to access data from computed property Vue.js

Issue

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

Solution

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>

Answered By – Bert

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.