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