在vue中使用回調(diào)函數(shù),this調(diào)用無效的解決
let self = this //使用新變量替換this,以免this無效
//updateStudentInfoToServer是一個將本身部分?jǐn)?shù)據(jù)異步上傳的接口,接收三個參數(shù),其中第一個是數(shù)據(jù),第二、三個是函數(shù),第二、三個函數(shù)使用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) //網(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)用,所以會先返回然后才執(zhí)行成功、失敗的回調(diào)。
這種書寫方式,function的作用于決定了function的代碼塊內(nèi)使用this無法改變、獲取vue data中設(shè)置的變量
使用es6的箭頭語法可以實現(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) } )
不過某些瀏覽器的某些版本不支持es6的語法,可能導(dǎo)致各種各樣的問題
補(bǔ)充知識:vue在全局函數(shù)中加回調(diào),調(diào)用vue文件中的函數(shù)
全局函數(shù)可以寫一個文件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文件中
調(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ù)編寫
test:function(str){ this.msg = '233' + str },
以上這篇在vue中使用回調(diào)函數(shù),this調(diào)用無效的解決就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue里面v-bind和Props 利用props綁定動態(tài)數(shù)據(jù)的方法
今天小編就為大家分享一篇vue里面v-bind和Props 利用props綁定動態(tài)數(shù)據(jù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08在Vue3.x中實現(xiàn)類似React.lazy效果的方法詳解
React 的 React.lazy 功能為組件懶加載提供了原生支持,允許開發(fā)者將組件渲染推遲到實際需要時再進(jìn)行,雖然 Vue3.x 沒有一個直接對應(yīng)的 lazy 函數(shù),但我們可以通過動態(tài)導(dǎo)入和 defineAsyncComponent 方法來實現(xiàn)類似的效果,需要的朋友可以參考下2024-03-03Element plus實現(xiàn)圖片手動上傳與回顯的過程
近期,發(fā)現(xiàn)點(diǎn)擊修改,element ui 的圖片沒有回顯到框中,所以本文給大家介紹了Element plus實現(xiàn)圖片手動上傳與回顯的過程,文中通過代碼示例給大家介紹的非常詳細(xì),具有一定的參考價值,需要的朋友可以參考下2024-09-09uniapp前端支付篇之微信、抖音、快手、h5四個平臺支付功能
支付功能在我們?nèi)粘i_發(fā)中經(jīng)常會遇到,下面這篇文章主要給大家介紹了關(guān)于uniapp前端支付篇之微信、抖音、快手、h5四個平臺支付功能的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-03-03