Using callback function in vue this calls invalid resolution

  • 2021-08-06 20:20:57
  • OfStack

let self = this//Replace this with a new variable to prevent this from being invalid

//updateStudentInfoToServer is an interface that uploads part of its own data asynchronously, receiving 3 parameters, the first of which is data, the second. 3 is function, and the second. 3 function is written in the form 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) // Successful callback of the network 
 
 }).catch(error=>{
  console.log(error)
  networkError(error) // Callback of network failure 
 }) 
 
 console.log('axios done')
}, 
 
this.updateStudentInfoToServer(data, function(res){
  console.log('return ok')
  console.log(res)
  // console.log('self')
  // console.log(self) // Is this
  // console.log('this')
  // console.log(this) //undefined
 
  self.handleCancelEdit()
 },function(error){
  console.log(error)
 }
 
)

Submitting network data is an asynchronous call, so it returns before performing successful or failed callbacks.

In this writing mode, the function of function determines that the code block of function cannot be changed by using this, and the variables set in vue and data are obtained

The arrow syntax of es6 can be used to call this everywhere


this.updateStudentInfoToServer(this, res=>{
  console.log('return ok')
  console.log(res)
  console.log('self')
  console.log(self)
  console.log('this')
 
  console.log(this)//this And self1 Sample 
 
 }, error=>{
  console.log(error)
 }
)

However, some versions of some browsers do not support the syntax of es 6, which can cause a variety of problems

Supplementary knowledge: vue adds callbacks to global functions and calls functions in vue files

Global function can write 1 file 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)

In the vue file

Call

this. testCallBack (this. test, 'yui0')//Modify the data in the vue file by calling a function in the vue file with a global function

this. setData (this, 'msg')//Use global functions to modify data in vue files

test Function Compilation


test:function(str){
 this.msg = '233' + str
}, 

Related articles: