vue created鈎子使用后台數據賦值給data里的變量,報錯‘undefined’


created: function () {
      this.$axios.post('/jsonData').then( function (res) {
        this.cares = res.data;
        console.log(this.cares)
      })
 
 以上報錯‘undefined’
 
經過查詢得知,.then回調里的this指向的不是vue實例,所以出錯。
 
解決辦法:
  1、修改this指向,原生js可以用.bind()方法
  2、ES6 箭頭函數
    
  .then(  res => {
        this.cares = res.data;
        console.log(this.cares)
      })
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM