从挂载函数内部调用Vue方法

编程入门 行业动态 更新时间:2024-10-14 14:22:31
本文介绍了从挂载函数内部调用Vue方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-27 00:23:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1145596.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   方法   Vue

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!