日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 前端技术 > vue >内容正文

vue

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

發(fā)布時(shí)間:2025/3/15 vue 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 vue 执行函数this_在vue中使用回调函数,this调用无效的解决 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

let self = this //使用新變量替換this,以免this無(wú)效

//updatestudentinfotoserver是一個(gè)將本身部分?jǐn)?shù)據(jù)異步上傳的接口,接收三個(gè)參數(shù),其中第一個(gè)是數(shù)據(jù),第二、三個(gè)是函數(shù),第二、三個(gè)函數(shù)使用function(){}形式書(shū)寫(xiě)

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) //網(wǎng)絡(luò)成功的回調(diào)

}).catch(error=>{

console.log(error)

networkerror(error) //網(wǎng)絡(luò)失敗的回調(diào)

})

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)

}

)

提交網(wǎng)絡(luò)數(shù)據(jù)是異步調(diào)用,所以會(huì)先返回然后才執(zhí)行成功、失敗的回調(diào)。

這種書(shū)寫(xiě)方式,function的作用于決定了function的代碼塊內(nèi)使用this無(wú)法改變、獲取vue data中設(shè)置的變量

使用es6的箭頭語(yǔ)法可以實(shí)現(xiàn)this的隨處調(diào)用

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)

}

)

不過(guò)某些瀏覽器的某些版本不支持es6的語(yǔ)法,可能導(dǎo)致各種各樣的問(wèn)題

補(bǔ)充知識(shí):vue在全局函數(shù)中加回調(diào),調(diào)用vue文件中的函數(shù)

全局函數(shù)可以寫(xiě)一個(gè)文件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文件中

調(diào)用

this.testcallback(this.test, 'yui0')//使用全局函數(shù)調(diào)用vue文件中的函數(shù),修改vue文件中的數(shù)據(jù)

this.setdata(this, 'msg')//使用全局函數(shù)修改vue文件中的數(shù)據(jù)

test函數(shù)編寫(xiě)

test:function(str){

this.msg = '233' + str

},

以上這篇在vue中使用回調(diào)函數(shù),this調(diào)用無(wú)效的解決就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持萬(wàn)仟網(wǎng)。

如您對(duì)本文有疑問(wèn)或者有任何想說(shuō)的,請(qǐng)點(diǎn)擊進(jìn)行留言回復(fù),萬(wàn)千網(wǎng)友為您解惑!

總結(jié)

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

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。