如何使用axios进行Vue和后端的数据交互?
axios的简单使用
Axios是一个开源的可以用在浏览器端和NodeJS的异步通信框架,它的主要作用就是实现Ajax异步通信。 1.安装axios
npm install axios vue-axios --save
2.在main.js中引入axios
import axios from axios Vue.config.productionTip = false; //设置默认请求的路径(http://localhost:8088为请求后端的路径) axios.defaults.baseURL = "http://localhost:8088" Vue.prototype.$axios = axios;
3.使用axios请求后端数据
<script> export default { name: "UserManager", data(){ return{ //声明student数组 student:[] } }, //vue生命周期钩子函数,用来初始数据 mounted(){ //初始化student this.getStudent(); }, methods : { //通过调用后端接口得到student集合 getStudent(){ //get为请求方式,请求路径为baseURL+即http://localhost:8088/student/index //then回调函数,res为请求返回的结果 this.$axios.get(/student/index).then(res =>{ console.log(res); //将res.data里面的数据赋值给student数组 this.student = res.data; }) }, del(id){ if (confirm("您确定要删除吗?")) { //带参用+号连接即可 this.$axios.get(/student/delete/+id).then(res =>{ if(res){ for (var i = 0; i <this.student.length ; i++) { if(id==this.student[i].id){ this.removeTodo(i) } } } }) } else { return false; } }, removeTodo (index){ this.student.splice(index, 1); } } } </script>
4.vue绑定数据
<template> <div> 用户首页 <table border="1px"> <thead> <tr> <th> <div><input type="checkbox"></div> </th> <th>id</th> <th>姓名</th> <th>年龄</th> <th>班级</th> <th>性别</th> <th>操作</th> </tr> </thead> <tbody> //使用v-for循环遍历 <tr v-for = "stu in student" :key="stu.id"> <td> <div><input type="checkbox"/></div> </td> //mustache语法{ {}}获取对象属性数据 <td>{ { stu.id}}</td> <td>{ { stu.name}}</td> <td>{ { stu.age}}</td> <td>{ { stu.classroom}}</td> <td>{ { stu.sex}}</td> <td> <a title="编辑" onclick="" href="javascript:;">编辑</a> <a title="删除" href="#" @click="del(stu.id)">删除</a> </td> </tr> </tbody> </table> </div> </template>