如何从方法内部访问数据
how to access data from inside a method
我是 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
感谢任何帮助。
亲切的问候。
不能在Vue实例中使用箭头函数引用this
来获取Vue实例数据,因为this
引用了window
,正确的ES6语法是:
setAccountType(typeId){
this.accountType = typeId
}
带箭头功能的 JSFiddle:https://jsfiddle.net/zxqohh0L/
带有非箭头 ES6 函数的 JSFiddle:https://jsfiddle.net/zxqohh0L/1/
您仍然可以在方法内部使用箭头函数。
我是 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
感谢任何帮助。
亲切的问候。
不能在Vue实例中使用箭头函数引用this
来获取Vue实例数据,因为this
引用了window
,正确的ES6语法是:
setAccountType(typeId){
this.accountType = typeId
}
带箭头功能的 JSFiddle:https://jsfiddle.net/zxqohh0L/
带有非箭头 ES6 函数的 JSFiddle:https://jsfiddle.net/zxqohh0L/1/
您仍然可以在方法内部使用箭头函数。