在vue中当在vue中使用匿名函数的时候,会出现this指针改变的问题,出现方法或者属性数据undefine
的问题,以下是相关的解决方法
一、在回调函数之前
重新将this赋值
例如
connection() {
// 更换that指针
var that = this
const socket = new SockJS('http://localhost:8080/test-info')
this.stompClient = Stomp.over(socket)
console.log('----------------')
console.log(this.stompClient)
console.log('----------------')
const tt = this.stompClient
// 此处不能使用 this.stompClient
tt.connect({}, function(frame) {
console.log('++++++++++++++++')
console.log('Connected: ' + frame)
console.log('++++++++++++++++')
tt.subscribe('/stock/price', function(val) {
console.log(val)
console.log(JSON.parse(val.body))
that.list1 = JSON.parse(val.body)
})
})
}
二、使用箭头函数
connection() {
// 更换that指针
const socket = new SockJS('http://localhost:8080/test-info')
this.stompClient = Stomp.over(socket)
console.log('----------------')
console.log(this.stompClient)
console.log('----------------')
this.stompClient.connect({}, (frame) => {
console.log(frame)
this.stompClient.subscribe('/stock/price', (val) => {
console.log('--------list1-----------')
console.log(this.list1)
console.log('--------list1-----------')
this.list1 = JSON.parse(val.body)
})
})
}
在回调函数中有时候回调函数会修改this的指向,this本来应该指的是vue这个对象,但是他的this指向的是回调,由于在回调函数改变了this指针,导致后序出现this指向的数据出现未定义的状况。
但是在箭头函数中this
指向的永远都是vue对象,所以建议多是想用箭头函数