1. 程式人生 > 程式設計 >在vue中使用回撥函式,this呼叫無效的解決

在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 '@/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呼叫無效的解決就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。