在vue中使用回调函数,this调用无效的解决
编程学习 2021-07-04 14:06www.dzhlxh.cn编程入门
这篇文章主要介绍了在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'
}
Vue.prototype.testCallMe = function(str){
console.log('test call me' + str)
}
Vue.prototype.testCallBack = function(func, param){
func(param)
this.testCallMe('tetetet')
}
}
main.js
import globalFunc from
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调用无效的解决就是长沙网络推广分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持狼蚁SEO。
上一篇:封装 axios+promise通用请求函数操作
下一篇:js实现简单抽奖功能
编程语言
- ThinkPad 笔记本如何调节LCD屏幕亮度
- Dreamweaver制作网页打开特效教程
- Win10 Mobile 10586升级后无限重启怎么办 硬重启帮您
- Win8系统提示音频设备有问题有一个或多个音频服
- Xbox One版Win10首个预览版9月份发布
- 如何在textarea文本输入区内实现换行
- Win10 Build 9901系统更新 预览版新版本下载
- McAfee Framework存在远程格式串处理漏洞
- Win10家庭版今日(7月30)正式在中国官方商城开卖
- Win10 Mobile预览版更新完10536.1000后才收到10536.100
- Win10 RS2更新了什么-Win10 RS2最终版本号1704首曝
- Windows7如何查看回收站对应的文件夹有哪些方法
- Win10让Charms栏回归桌面的方法教程
- 取消Windows XP系统开机启动画面的小技巧
- win8系统怎么下载安装USB百兆网卡?
- XP系统下磁盘空间变少了怎么办?XP系统磁盘空间