【发布时间】:2018-05-30 19:17:19
【问题描述】:
我有一个具有以下结构的 vue 组件:
export default{
name: '',
data: function () {
return {
var1 :{},
var2 : {},
...
}
},
created: function () {
this.methodName1()
},
methods: {
methodName2: function () {
var context = this
rp(options).then(function () {
context.methodName1()
return null
}).catch(function (err) {
console.log(err)
})
},
methodName1: function () {
//function body
}
}
我的疑问是为什么this.methodName1 给出 undefined where as
var context = this;
context.methodName1
在 methodName2 中工作得很好吗?
为什么我们需要引用 this 变量来修改 DOM 元素?
【问题讨论】:
-
是你的问题,为什么你不能在methodName2的
then回调中写this.methodName1()? -
是的,不仅在回调外也回调
-
VueJS 为
methods牵着你的手,将他们的this重新连接成更复杂的对象。但它不会对方法内的代码执行此操作。您将使用胖箭头函数 - 或显式存储上下文,就像您在那个 sn-p 中所做的那样。 -
好的。我明白了一点,但我的困惑仍然在于 1。为什么我们将对此的引用存储在另一个变量中? 2.为什么直接使用this不起作用? (
var context = this; context.methodName1和this.methodName1()不一样)
标签: javascript vue.js scope this