日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

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

發布時間:2025/3/15 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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

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調用無效的解決就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持萬仟網。

如您對本文有疑問或者有任何想說的,請點擊進行留言回復,萬千網友為您解惑!

總結

以上是生活随笔為你收集整理的vue 执行函数this_在vue中使用回调函数,this调用无效的解决的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。