報(bào)錯(cuò)場(chǎng)景:將APi中得到的response數(shù)據(jù),用Vue$set()使數(shù)據(jù)動(dòng)態(tài)響應(yīng)
報(bào)錯(cuò)代碼:
methods: { textTranslate: function (text, to) { $.ajax({ url: 'http://openapi.youdao.com/api', type: 'post', dataType: 'jsonp', data: { q: text, appKey: this.appKey, salt: this.salt, from: this.from, to: to, sign: md5(this.appKey + text + this.salt + this.key) }, success: function (data) { this.$set(this.$data, 'translatedText', data.translation[0]) } }) } }
報(bào)錯(cuò)原因:這里的this指向的不是VueModel,
解決方法1:在執(zhí)行函數(shù)中定義指向Model的變量 let vm = this ,用該變量替代this
methods: { textTranslate: function (text, to) { let vm = this $.ajax({ url: 'http://openapi.youdao.com/api', type: 'post', dataType: 'jsonp', data: { q: text, appKey: this.appKey, salt: this.salt, from: this.from, to: to, sign: md5(this.appKey + text + this.salt + this.key) }, success: function (data) { vm.$set(vm.$data, 'translatedText', data.translation[0]) } }) } }
解決方法2:將。siccess改為箭頭函數(shù)的寫法,這樣子箭頭函數(shù)里的this其實(shí)是指向VueModel的,這樣子用this看不會(huì)報(bào)錯(cuò)了
success: (data) => { this.$set(this.$data, 'translatedText', data.translation[0]) }
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com