繁体   English   中英

vue.js 不能在创建的函数内调用函数

[英]vue.js cannot call function inside a function in created

我正在尝试使用 sweetalert 在 vue.js 中编写对 websocket 消息的响应。

遗憾的是,我无法调用 sweetalert 或我在创建的 onmessage 内的方法中定义的函数。

未捕获的类型错误:this.confirmation 不是 WebSocket.connection.onmessage 的函数

  methods: {
    confirmation(response) {
      if (response.data == "stop") {
        this.$swal({
          icon: "success",
          text: "stopped!",
        });
      }
      if (response.data == "start") {
        this.$swal({
          icon: "success",
          text: "started!",
        });
      }
    },
  },
  created() {
    this.connection.onmessage = function(event) {
      console.log(event.data);
      this.confirmation(event);
    };
  },

这应该有效:

created() {
    const that = this;
    this.connection.onmessage = function(event) {
      console.log(event.data);
      that.confirmation(event);
    };
}

function关键字定义的function有自己的this 使用that变量会保留外部作用域的this以便内部作用域可以访问它。

我认为这是与使用的问题this ,因为它看起来像你的方法被称为在错误的上下文。 在 js 中使用 this 的详细信息在这里 我可能只是在别处定义函数,您可以在不使用this情况下访问它。 可能有更优雅的方式,但老实说,我不熟悉 javascript 的深度

虽然@Neferin 的答案通常是正确的,但您可以使用箭头函数来处理这样的情况。 很快,用function关键字定义的function有它自己的作用域,这意味着它有它自己的this 箭头函数没有作用域。

下面是一个例子:

 created() {
    this.connection.onmessage => (event) {
      //                     ^^^^
      // in the arrow function this is a parent scope
      console.log(event.data);
      this.confirmation(event);
    };
  },

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM