问题描述
限时送ChatGPT账号..在我的 Vue 挂载代码中,我通过 this.test() 调用函数测试.这按预期工作正常.
In my Vue mounted code, I am calling a function test via this.test(). This works fine as intended.
然而,当我从新的 ResizeObserver 函数调用 this.test() 时,出现错误
When however I am calling this.test() from the new ResizeObserver function, I am getting an error
this.test 不是函数
this.test is not a function
我知道这是因为 this
现在指向 resizeObserver.我不明白的是我应该在那里使用什么.删除 this 也会出错.
I understand that this is because the this
there is now pointing to the resizeObserver. What I do not understand is what I should use there instead. Removing the this also gives an error.
我有以下Vue代码
mounted: function() {
this.test();
new ResizeObserver(function() {
this.test();
}).observe(this.g("tC"));
},
methods: {
test: function() {}
....
}
推荐答案
您应该将this"绑定到传递给 ResizeObserver 的函数
You should either bind "this" to the function passed to ResizeObserver
mounted: function() {
this.test();
new ResizeObserver(function() {
this.test();
}.bind(this)).observe(this.g("tC"));
},
或者使用箭头函数(如果您的环境支持 ES6),因为箭头函数使用外部作用域的this"值:
Or use an arrow function (if your environment supports ES6) since arrow functions use "this" value of the outer scope:
mounted: function() {
this.test();
new ResizeObserver(() => {
this.test();
}).observe(this.g("tC"));
},
这篇关于从挂载函数内部调用Vue方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论