Vue 回调函数中this无效

记录在vue项目中使用回调函数时调用this无效问题

vue 在回调函数中 this 并不是指向 vue 实例,我在回调函数中打印了下,结果是undefined,而网上的一些博客说是 window 或 undefined,这里 window 没有出来,可能和我写的函数有关系,以后碰到再说。

直接上解决方案:

1、在回调函数之前将 vue 实例 this 赋值给一个变量,在回调函数中使用该变量
requestHistoryList (mobileNumber, channelIndex) {
	......
	var _that = this
    this.sendCommand(url, params,function (ret) {
      	console.log(_that)
      	if (ret.code == 0) {
        	if (ret.data.sendResult == "SUCCESS") {
          		var parse = JSON.parse(ret.data.params);
          		_that.playBackVideoList = parse.infos
          		console.log(_that.playBackVideoList)
        	}
      	}else {
        	alert(ret.msg);
	  	}
    })
},
2、使用箭头函数

箭头函数和匿名函数有个明显的区别:箭头函数内部的this是词法作用域,由上下文确定。箭头函数完全修复了this的指向,this总是指向词法作用域。

requestHistoryList (mobileNumber, channelIndex) {
	......
    this.sendCommand(url, params, (ret) => {
      	if (ret.code == 0) {
        	if (ret.data.sendResult == "SUCCESS") {
          		var parse = JSON.parse(ret.data.params);
          		this.playBackVideoList = parse.infos
          		console.log(this.playBackVideoList)
        	}
      	}else {
        	alert(ret.msg);
	  	}
    })
},
3、在 methods 中定义一个函数,回调函数使用该函数
requestHistoryList (mobileNumber, channelIndex) {
	......
    this.sendCommand(url, params, this.paresVideoData)
},
paresVideoData (ret) {
  	if (ret.code == 0) {
       	if (ret.data.sendResult == "SUCCESS") {
          	var parse = JSON.parse(ret.data.params);
          	this.playBackVideoList = parse.infos
          	console.log(this.playBackVideoList)
        }
     }else {
       	alert(ret.msg);
     }
},
  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值