how to access data from inside a method
Asked Answered
G

1

12

I'm new to vue.js. I'm starting to migrate my angularjs app. I'm using vue cli to generate a new simple-webpack project. This creates a new webpack+vueLoader project. Everything went smoothly but now I have an issue. on my @click event I want to change my data but I can't access the object. 'this' is not the data instance.

What am I missing here?

<template>
    <input type="radio" name="account-type" @click="setAccountType(item.id)"/><span>{{item.name}}</span>
</template>
<script>
  export default {
     data() {
        return { accountType: null
     },
     methods: { setAccountType: (typeId) => this.accountType = typeId
  }
</script>

this is not the data instance as expected and thus ui not updated. In vuejs doc i can see just addressing this is sufficient while in a method: vue js doc

Any help is appreciated.

Kind regards.

Grudging answered 13/12, 2016 at 11:8 Comment(0)
B
22

You cannot use an arrow function to refer to this inside a Vue instance to get Vue instance data because this refers to window, the correct ES6 syntax is:

 setAccountType(typeId){
   this.accountType = typeId
 }

JSFiddle with Arrow function: https://jsfiddle.net/zxqohh0L/

JSFiddle with non arrow ES6 function: https://jsfiddle.net/zxqohh0L/1/

You can still use arrow functions inside the methods themselves.

Banlieue answered 13/12, 2016 at 11:19 Comment(5)
outstanding answer. thank you very much for the effortGrudging
Very good explanation, I was digging to access the data inside a function with arrow function. Your answer really fixed my issue and also help to understand better.Loupgarou
Thank you very much! two hours wasted on this. It was driving me crazy.Hispid
It's too bad that using an arrow function completely breaks data binding, and you don't get a meaningful error message about it either. You'd think that the Vue instance would check for this and issue a warning.Disorient
Thanks. This didn't work because i was using an arrow function, as you said.Surveillance

© 2022 - 2024 — McMap. All rights reserved.