网络编程 
首页 > 网络编程 > 浏览文章

在vue中使用回调函数,this调用无效的解决

(编辑:jimmy 日期: 2025/2/25 浏览:3 次 )

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 '@/components/globalFunc'

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调用无效的解决就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

上一篇:封装 axios+promise通用请求函数操作
下一篇:vue 调用 RESTful风格接口操作
一句话新闻
一文看懂荣耀MagicBook Pro 16
荣耀猎人回归!七大亮点看懂不只是轻薄本,更是游戏本的MagicBook Pro 16.
人们对于笔记本电脑有一个固有印象:要么轻薄但性能一般,要么性能强劲但笨重臃肿。然而,今年荣耀新推出的MagicBook Pro 16刷新了人们的认知——发布会上,荣耀宣布猎人游戏本正式回归,称其继承了荣耀 HUNTER 基因,并自信地为其打出“轻薄本,更是游戏本”的口号。
众所周知,寻求轻薄本的用户普遍更看重便携性、外观造型、静谧性和打字办公等用机体验,而寻求游戏本的用户则普遍更看重硬件配置、性能释放等硬核指标。把两个看似难以相干的产品融合到一起,我们不禁对它产生了强烈的好奇:作为代表荣耀猎人游戏本的跨界新物种,它究竟做了哪些平衡以兼顾不同人群的各类需求呢?