国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

在vue中使用回調函數,this調用無效的解決

瀏覽:94日期:2022-12-09 18:24:43

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

標簽: Vue
主站蜘蛛池模板: 沿河| 宁河县| 新蔡县| 南丰县| 武定县| 无极县| 承德县| 新晃| 桂阳县| 灌云县| 阳山县| 石泉县| 临清市| 昭通市| 铜山县| 温宿县| 乐亭县| 温宿县| 林甸县| 偏关县| 广东省| 普格县| 景东| 徐闻县| 靖江市| 上虞市| 临泽县| 姚安县| 连云港市| 黔西| 枣阳市| 闵行区| 平塘县| 柳河县| 洪雅县| 玛多县| 溧水县| 长汀县| 文化| 睢宁县| 大同市|