Vue调用this.addRow报Uncaught TypeError: this.method is not a function求助
错误根源
你遇到的报错是回调函数的this指向上下文错误导致的:this.connection.onmessage的回调你用了普通匿名函数,普通函数的this会自动绑定到触发事件的WebSocket实例身上,而不是你的Vue组件实例,自然找不到定义在methods里的addRow方法。
修复方案
以下3种方案任选一种即可:
- 方案1:把回调改为箭头函数(最常用)
箭头函数不会自行绑定this,会继承外层作用域的this,也就是mounted钩子对应的Vue组件实例
mounted: function() { console.log('Starting connection to WebSocket Server'); this.connection = new WebSocket('ws://localhost:8080/pos-detail'); // 替换普通function为箭头函数 this.connection.onmessage = (event) => { console.log('Server message : ' + event.data); this.posArray = event.data.split(';'); if(this.posArray.length > 2) { this.addRow(this.posArray[0], this.posArray[7]); } } }
- 方案2:提前保存Vue实例指向
在回调外层把Vue实例的this存为临时变量,回调内直接用临时变量调用方法
mounted: function() { console.log('Starting connection to WebSocket Server'); // 提前保存Vue实例指向 const vm = this; this.connection = new WebSocket('ws://localhost:8080/pos-detail'); this.connection.onmessage = function(event) { console.log('Server message : ' + event.data); vm.posArray = event.data.split(';'); if(vm.posArray.length > 2) { vm.addRow(vm.posArray[0], vm.posArray[7]); } } }
- 方案3:用bind手动绑定this
通过bind方法强制把回调内的this绑定为Vue组件实例
mounted: function() { console.log('Starting connection to WebSocket Server'); this.connection = new WebSocket('ws://localhost:8080/pos-detail'); this.connection.onmessage = function(event) { console.log('Server message : ' + event.data); this.posArray = event.data.split(';'); if(this.posArray.length > 2) { this.addRow(this.posArray[0], this.posArray[7]); } // 绑定this为当前Vue实例 }.bind(this) }
补充注意:如果你的
newPos、no属性没有在组件的data选项里提前初始化的话,后续更新可能不会触发视图响应,建议提前在data中声明对应属性的初始值。
内容的提问来源于stack exchange,提问作者panoet
相关产品推荐
相关产品推荐

