Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access data from computed property Vue.js

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

like image 614
Valchulen Avatar asked Mar 17 '17 23:03

Valchulen


People also ask

Can you watch a computed property Vue?

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.

Can I use computed in data Vue?

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.


1 Answers

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>
like image 113
Bert Avatar answered Oct 02 '22 14:10

Bert