问题:
用ajax或者axios,get数据是正常的。但是渲染数据时data一直为空
问题代码:
下面代码看起来是正常的,但是当运行的时候会报错: 这时候你运行时会发现,数据可以请求到,但是会报错TypeError: Cannot set property ‘dataList’ of undefined
data () { return { dataList:[], } }, mounted(){ this.getDataList() }, methods:{ getDataList(){ //用axios获取数据 axios({ method:'get', url:'/api/info' }) .then(function(response){ console.log(response.data) this.listClass = response.data }).catch(function(error){ // 请求失败处理 console.log(error); });
//用ajax获取数据
$.ajax({
url: '/api/devices',
method: 'GET',
dataType: 'JSON',
async:false,
success: function(data) {
that.listClass = data
}
})
}
} 主要原因是:
在ajax中的this会指向ajax本身,而不再是vue实例本身 ,同理,axios的then中this也不是指向vue实例本身
解决办法:
方法1: 用ES6箭头函数,箭头方法可以和父方法共享变量 ( ES6中的 箭头函数 “=>” 内部的this是词法作用域,由上下文确定(也就是由外层调用者vue来确定) )
axios({ method:'get', url:'/api/info' }) .then((response) => { console.log(response.data) that.listClass = response.data }).catch((error) => { // 请求失败处理 console.log(error); }); 方法2: 在请求axios外面定义一下 var that=this
//用axios获取数据 var that = this axios({ method:'get', url:'/api/info' }) .then(function(response){ console.log(response.data) that.listClass = response.data }).catch(function(error){ // 请求失败处理 console.log(error); }); 拓展:
vue项目怎么引入全局的axios? 下载:
npm install axios --save 引入:
import axios from "axios" Vue.prototype.$axios = axios 使用:
this.$axios({ url: "api/login", method: "post" })
———————————————— 版权声明:本文为CSDN博主「weixin_55560445」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:blog.csdn.net/weixin_5556…