解决this调用无效的问题

发布时间:2020-08-12 11:55:28 作者:小新
来源:亿速云 阅读:553

这篇文章将为大家详细讲解有关解决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 '@/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
}, 

关于解决this调用无效的问题就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. 解决thinkphp设置session周期无效的问题
  2. 如何解决SqlDataReader指定转换无效的问题

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue 回调函数 this

上一篇:SpringMvc web.xml是如何配置实现的

下一篇:c++如何禁止函数的传值调用操作

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》