1. Vue中如何引入Ajax - axios
<!--引入Axios实现Ajax请求 -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
2. Ajax - axios发送请求与响应
const app = new Vue({
el:'#app',
data:{
baseURL: "http://xxx:8000/",
students:[],
},
mounted: function() { //mounted是Vue生命周期函数,加载数据时调用getStudents方法
this.getStudents();
},
methods:{
getStudents:function(){
let that = this //Ajxa请求后会释放this对象,需要保存this的地址为that
axios
.get(that.baseURL + 'students/')
.then(function(response){ //前端 通过response对象获取后端数据
if (response.data.code ===1){ //判断后端,后端定义:key=code,value=1
//请求成功后,数据传递
that.students = response.data.data //后端定义:key=data,value传给js对象that.students,再通过html显示
//提示成功的提示
that.$message({
message: '数据加载成功',
type: 'success'
});
}
else{
//提示失败的提示
that.$message.error(response.data.msg);
}
})
.catch(function(error){
console.log(error);
});
},
},
})