let self = this //使用新变量替换this,以免this无效
//updatestudentinfotoserver是一个将本身部分数据异步上传的接口,接收三个参数,其中第一个是数据,第二、三个是函数,第二、三个函数使用function(){}形式书写
updatestudentinfotoserver:function(data, networkok, networkerror){
let postdata = this.$qs.stringify({
data:data
})
this.axios.post('/api/update/updatestudentinfo',
postdata
).then(res=>{
console.log(' return : ')
console.log(res)
networkok(res) //网络成功的回调
}).catch(error=>{
console.log(error)
networkerror(error) //网络失败的回调
})
console.log('axios done')
},
this.updatestudentinfotoserver(data, function(res){
console.log('return ok')
console.log(res)
// console.log('self')
// console.log(self) //就是this
// console.log('this')
// console.log(this) //undefined
self.handlecanceledit()
},function(error){
console.log(error)
}
)
提交网络数据是异步调用,所以会先返回然后才执行成功、失败的回调。
这种书写方式,function的作用于决定了function的代码块内使用this无法改变、获取vue data中设置的变量
使用es6的箭头语法可以实现this的随处调用
this.updatestudentinfotoserver(this, res=>{
console.log('return ok')
console.log(res)
console.log('self')
console.log(self)
console.log('this')
console.log(this)//this和self一样
}, error=>{
console.log(error)
}
)
不过某些浏览器的某些版本不支持es6的语法,可能导致各种各样的问题
补充知识:vue在全局函数中加回调,调用vue文件中的函数
全局函数可以写一个文件globalfunc.js
exports.install = function(vue, option){
vue.prototype.setdata = function(that, key){
that[key] = '222'
}
vue.prototype.testcallme = function(str){
console.log('test call me' + str)
}
vue.prototype.testcallback = function(func, param){
func(param)
this.testcallme('tetetet')
}
}
main.js
vue.use(globalfunc)
vue文件中
调用
this.testcallback(this.test, 'yui0')//使用全局函数调用vue文件中的函数,修改vue文件中的数据
this.setdata(this, 'msg')//使用全局函数修改vue文件中的数据
test函数编写
test:function(str){
this.msg = '233' + str
},
以上这篇在vue中使用回调函数,this调用无效的解决就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持萬仟网。
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!