如何从方法内部访问数据

Gal*_*Ziv 10 vue.js vue-loader

我是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>
Run Code Online (Sandbox Code Playgroud)

这不是预期的数据实例,因此不会更新.在vuejs doc中,我可以看到只是在一个方法中解决这个问题就足够了: vue js doc

任何帮助表示赞赏.

亲切的问候.

cra*_*g_h 20

您不能使用箭头函数来引用thisVue实例内部以获取Vue实例数据,因为this参考window,正确的ES6语法是:

 setAccountType(typeId){
   this.accountType = typeId
 }
Run Code Online (Sandbox Code Playgroud)

JSFiddle with Arrow功能:https://jsfiddle.net/zxqohh0L/

JSFiddle与非箭头ES6功能:https://jsfiddle.net/zxqohh0L/1/

您仍然可以在方法本身中使用箭头函数.