【问题标题】:vue.js cannot call function inside a function in createdvue.js 无法在创建的函数内调用函数
【发布时间】:2020-12-30 02:10:57
【问题描述】:

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

遗憾的是,我无法调用 sweetalert 或我在 created 的 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);
    };
  },

【问题讨论】:

    标签: javascript vue.js websocket typeerror sweetalert


    【解决方案1】:

    虽然@Neferin 的回答通常是正确的,但您可以使用arrow function 来处理此类情况。使用function 关键字定义的函数有自己的范围,这意味着它有自己的this。箭头函数没有范围。

    这是一个例子:

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

    【讨论】:

    • 哦,比古代问题:3
    【解决方案2】:

    这应该可行:

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

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

    【讨论】:

    • 一个好的答案将始终包含解释为什么这会解决问题,以便 OP 和任何未来的读者可以从中学习
    • 您已经确定了根本原因。这是一个很好的例子来解释 OP 做错了什么。在了解了这个上下文之后,OP 应该考虑使用箭头函数。
    【解决方案3】:

    我认为这是this 使用的问题,因为您的方法似乎是在错误的上下文中调用的。 Details on the usage of this in js here。 我可能只是在别处定义函数,您可以在不使用this 的情况下访问它。可能有更优雅的方式,但老实说我不熟悉 javascript 的深度

    【讨论】:

      猜你喜欢
      • 2021-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多