简体   繁体   English

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

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

I'm trying to code a response to websocket messages in vue.js using sweetalert.我正在尝试使用 sweetalert 在 vue.js 中编写对 websocket 消息的响应。

Sadly I cannot call sweetalert or a function I defined in methods inside the onmessage in created.遗憾的是,我无法调用 sweetalert 或我在创建的 onmessage 内的方法中定义的函数。

Uncaught TypeError: this.confirmation is not a function at WebSocket.connection.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);
    };
  },

This should work:这应该有效:

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

Functions that are defined with the function keyword have their own this .function关键字定义的function有自己的this Using the that variable preserves the outer scope's this so the inner scope can access it.使用that变量会保留外部作用域的this以便内部作用域可以访问它。

I think this is a problem with the usage of this , as it seems like your method is called in the wrong context.我认为这是与使用的问题this ,因为它看起来像你的方法被称为在错误的上下文。 Details on the usage of this in js here . 在 js 中使用 this 的详细信息在这里 I'd problably just define the function elsewhere, where you can access it without using this .我可能只是在别处定义函数,您可以在不使用this情况下访问它。 There might be an more elegant way, but I'm honestly not to familiar with the indepths of javascript可能有更优雅的方式,但老实说,我不熟悉 javascript 的深度

While @Neferin 's answer is generally correct, you can use arrow function to handle cases like this.虽然@Neferin 的答案通常是正确的,但您可以使用箭头函数来处理这样的情况。 Shortly function defined with a function keyword has it's own scope, means has it's own this .很快,用function关键字定义的function有它自己的作用域,这意味着它有它自己的this Arrow-function does not have a scope.箭头函数没有作用域。

Here is an example:下面是一个例子:

 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