五、axios
axios是独立于vue的一个项目,基于promise用于浏览器和node.js的http客户端
在浏览器中可以帮助我们完成 ajax请求的发送,在node.js中可以向远程接口发送请求
1、获取数据
<script src="axios.min.js"></script>
注意:测试时需要开启后端服务器,并且后端开启跨域访问权限
data: {
teacher: {}
},
created() {
// 向具有指定ID的用户发出请求
this.getById(73)
},
methods: {
getById(id) {
vm = this
axios.get('http://localhost:8082/admin/edu/teacher/' + id)
.then(function (response) {
console.log(response)
vm.teacher = response.data.data
}).catch(function (error) {
console.log(error)
})
}
}
控制台查看输出
2、回显数据
<!-- 修改 -->
<form action="">
<label>id:<input type="text" v-model="teacher.teacherId"></label>
<label>姓名:<input type="text" v-model="teacher.name"></label>
</form>
3、更新数据
<!-- 修改 -->
<form action="">
......
<button type="button" @click="update">修改</button>
</form>
methods: {
......,
update(){
// 发起一个PUT请求
axios({
method: 'put',
url: 'http://localhost:8082/admin/edu/teacher/' + this.teacher.teacherId,
data: this.teacher
}).then(function (response) {
console.log(response)
console.log('修改成功')
}).catch(function (error) {
console.log(error)
})
}
}
4、显示数据列表
data: {
......,
listQuery: {
page: 1,
limit: 10,
searchObj: {}
}
teacherList: []//数组
},
created() {
......
this.getList()
},
methods: {
......,
getList(){
//TODO
}
}
<!-- 查询 -->
<form action="">
<input type="text" placeholder="讲师名" v-model="listQuery.searchObj.name">
<select v-model="listQuery.searchObj.level">
<option value="">请选择</option>
<option value="1">高级讲师</option>
<option value="2">首席讲师</option>
</select>
<label>
添加时间
<input type="text" placeholder="选择开始时间" v-model="listQuery.searchObj.begin">
<input type="text" placeholder="选择结束时间" v-model="listQuery.searchObj.end">
</label>
<button type="button" @click="getList">查询</button>
</form>
getList(){
vm = this
// 发起一个POST请求
axios({
method: 'post',
url: `http://localhost:8082/admin/edu/teacher/${this.listQuery.page}/${this.listQuery.limit}`,
data: this.listQuery.searchObj
}).then(function (response) {
// console.log(response)
vm.teacherList = response.data.data
}).catch(function (error) {
console.log(error)
})
}
<table border="1">
<tr>
<td>id</td>
<td>姓名</td>
<td>头衔</td>
<td>添加时间</td>
</tr>
<tr v-for="item in teacherList">
<td>{{item.teacherId}}</td>
<td>{{item.name}}</td>
<td>{{item.level}}</td>
<td>{{item.createTime}}</td>
</tr>
</table>