在vue中使⽤回调函数,this调⽤⽆效的解决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'
}
stCallMe = function(str){
console.log('test call me' + str)
}
stCallBack = function(func, param){
func(param)
}
}
main.js
import globalFunc from '@/components/globalFunc'
Vue.use(globalFunc)
vue⽂件中
调⽤
this.setData(this, 'msg')//使⽤全局函数修改vue⽂件中的数据
test函数编写
test:function(str){
this.msg = '233' + str
},
函数prototype
以上这篇在vue中使⽤回调函数,this调⽤⽆效的解决就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。