Springboot和Vue简单的前后端数据交互
使用axios来进行数据交互。
1.SpringBoot环境搭建
准备一个简单的SpringBoot工程并且可以访问数据库返回数据。这里省略。。。
@Controller @RequestMapping("account") public class AccountController { @Autowired private AccountService accountService; @GetMapping("{id}") @ResponseBody public Account queryAccountById(@PathVariable("id") int id) { Account account = this.accountService.queryAccountById(id); return account; } @GetMapping("find") @ResponseBody // 这个要加偶,注意一下 public List<Account> findAll() { List<Account> all = this.accountService.findAll(); return all; } @RequestMapping("/") public String login() { return "test"; } }
2.Vue的环境的搭建安装Vue和axios的环境
npm init -y 初始化 npm install vue --save 安装Vue npm install axios 安装axios
3.页面准备
在templates下创建一个页面为test.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <div v-if="userList.length"> <table> <thead> <tr> <th>编号</th> <th>姓名</th> <th>资金</th> </tr> </thead> <tbody> <tr v-for="item in userList"> <td>{ { item.id}}</td> <td>{ { item.name}}</td> <td>{ { item.money}}</td> </tr> </tbody> </table> </div> <div v-else> <h2>数据为空!</h2> </div> </div> </body> <script src="./node_modules/vue/dist/vue.js"></script> <script src="./node_modules/axios/dist/axios.js"></script> <script type="text/javascript"> // get的访问方式 var vm = new Vue({ el:"#app", data:{ user: { id: "", name: "", money: "" }, userList: [] }, methods: { findAll:function () { // 在当前方法定义一个变量,表名是vue对象 var _this = this; axios.get(/account/find) .then(function (response) { // 函数执行成功后执行的函数 _this.userList = response.data; // 响应结果的数据给userList console.log(response); }) .catch(function (error) { // 函数执行失败后执行的函数 console.log(error); }) } }, created:function () { this.findAll(); } }) </script> </html> 其他方式: axios.get(url[, config]) axios.delete(url[, config]) axios.head(url[, config]) axios.post(url[, data[, config]]) axios.put(url[, data[, config]]) axios.patch(url[, data[, config]]
4.测试结果
编号 姓名 资金 1 董小二 700 2 婉儿 1100 4 小梦 23113 5 潭溪梦 10000