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