前后端分离基础入门(3) 数据对接
在写好简单的前端和后端项目后就可以进行数据对接操作了
我们使用axios技术去获得后端的JSON数据
前端axios安装
脚手架输入命令vue add axios添加插件
安装完成后会出现该文件夹

axios使用
由于我们需要在前端页面加载前去读取到数据并渲染 我们将该读取放在创建函数里即可
created() {
axios.get('http://localhost:8181/book/findAll').then(function (resp){
console.log(resp)
})
}
测试发现出现错误

需要解决跨域问题
解决跨域问题
最简单的方法 直接在控制类上加上@CrossOrigin注解

重新测试发现成功获得数据!

对数据进行渲染
完善创建函数代码
注意细节 用到回调函数时 提前用一个变量保存this
created() {
const _this=this//保存this 在回调函数时可以正常使用
axios.get('http://localhost:8181/book/findAll').then(function (resp){
_this.books=resp.data
})
}
访问页面发现前端成功获得后端数据!

前端页面完整代码
<template>
<div>
<table>
<tr>
<td>编号</td>
<td>图书名称</td>
<td>作者</td>
</tr>
<tr v-for="book in books">
<td>{{book.id}}</td>
<td>{{book.name}}</td>
<td>{{book.author}}</td>
</tr>
</table>
</div>
</template>
<script>
export default {
name: "Book",
data(){
return {
books:[
{
id: 1,
name: 'java',
author: 'jie'
},
{
id: 2,
name: 'vue',
author: 'jiejie'
},
{
id: 3,
name: 'springboot',
author: '张三'
}
]
}
},
created() {
const _this=this//保存this 在回调函数时可以正常使用
axios.get('http://localhost:8181/book/findAll').then(function (resp){
_this.books=resp.data
})
}
}
</script>
<style scoped>
</style>

浙公网安备 33010602011771号