如何解决vue.js无法在创建的函数中调用函数
我正在尝试使用sweetalert在vue.js中编写对Websocket消息的响应的代码。
可悲的是,我无法调用sweetalert或在我创建的onmessage中的方法中定义的函数。
未捕获的TypeError: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
的使用有关,因为似乎在错误的上下文中调用了您的方法。 Details on the usage of this in js here。
我可能只是在其他地方定义函数,而无需使用this
就可以在其中访问它。也许有一种更优雅的方法,但是老实说,我不熟悉javascript的深入知识
虽然@Neferin 的回答通常是正确的,但您可以使用 arrow function 来处理这样的情况。很快,用 function
关键字定义的函数有它自己的作用域,意味着有它自己的 this
。箭头函数没有作用域。
这是一个例子:
created() {
this.connection.onmessage => (event) {
// ^^^^
// in the arrow function this is a parent scope
console.log(event.data);
this.confirmation(event);
};
},
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。