Vue 報錯TypeError: this.$set is not a function 的解決方法

報錯場景:將APi中得到的response數據,用Vue$set()使數據動態響應

報錯代碼:

  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])
        }
      })
    }
  }

報錯原因:這裏的this指向的不是VueModel,

解決方法1:在執行函數中定義指向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改爲箭頭函數的寫法,這樣子箭頭函數裏的this其實是指向VueModel的,這樣子用this看不會報錯了

success: (data) => {
          this.$set(this.$data, 'translatedText', data.translation[0])
        }




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章