溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Vue報(bào)TypeError: this.$set is not a function錯(cuò)誤怎么辦

發(fā)布時(shí)間:2021-07-12 12:22:11 來源:億速云 閱讀:3004 作者:小新 欄目:web開發(fā)

這篇文章主要為大家展示了“Vue報(bào)TypeError: this.$set is not a function錯(cuò)誤怎么辦”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“Vue報(bào)TypeError: this.$set is not a function錯(cuò)誤怎么辦”這篇文章吧。

報(bào)錯(cuò)場景:將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])
    }

以上是“Vue報(bào)TypeError: this.$set is not a function錯(cuò)誤怎么辦”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI