2016-12-13 19 views
7

我是vue.js的新手。我開始移植我的angularjs應用程序。 我使用vue cli來生成一個新的simple-webpack項目。 這將創建一個新的webpack + vueLoader項目。 一切都很順利,但現在我有一個問題。我的@click事件中的 我想更改我的數據,但無法訪問該對象。 「this」不是數據實例。如何從方法內部訪問數據

我在這裏錯過了什麼?

<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> 

這不是預期的數據實例,因此ui沒有更新。 在vuejs文檔我可以看到只是解決這個是足夠的,而在一種方法: vue js doc

任何幫助表示讚賞。

親切的問候。

回答

15

不能使用箭頭功能是指一個Vue的實例裏面this得到Vue的實例數據,因爲thiswindow,正確ES6語法是:

setAccountType(typeId){ 
    this.accountType = typeId 
} 

的jsfiddle與Arrow功能:https://jsfiddle.net/zxqohh0L/

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

你仍然可以在他們的方法中使用箭頭函數自我。

+0

優秀的答案。非常感謝你的努力 –

+0

非常好的解釋,我正在挖掘訪問帶箭頭功能的函數內的數據。你的回答確實解決了我的問題,也有助於更好地理解。 – krrr25

+0

非常感謝!浪費了兩個小時。這讓我瘋狂。 –