Vue开发实例(七)Axios的安装与使用
说明:
- 如果只是在前端,axios常常需要结合mockjs使用,如果是前后端分离,就需要调用对应的接口,获取参数,传递参数;
- 由于此文章只涉及前端,所以我们需要结合mockjs使用;
- 由于为了方便实现效果,在这篇文章里面使用的是一级菜单,对应的代码是:【Vue开发实例(六)实现左侧菜单导航 —>>> 动态实现一级菜单】中的代码
- 文末附全部代码
axios和mockjs的安装与使用
- 一、Axios
- 1、安装axios
- 2、安装mockjs
- 二、数据请求
- 1、get请求
- 2、post请求
- 3、添加数据
- 4、修改
- 5、删除
- 6、查询
- (1)无参查询
- (2)有参查询
一、Axios
Axios 是一个基于 promise 的 HTTP 库,类似于我们常用的 ajax。
在开发过程中,特别是前后端分离的项目,比如前端用Axios、ajax请求后端数据,后端也许当前只给了接口文档,还没有数据的返回,导致前端无法进行测试、调试,现在可以使用mock.js拦截前端ajax请求,更加方便的构造你需要的数据,大大提高前端的开发效率。
1、安装axios
npm install axios --save
在main.js全局引入axios
import axios from 'axios'; Vue.prototype.$axios =axios;
2、安装mockjs
npm install mockjs --save-dev
在src下创建文件夹mock,并创建index.js文件,输入以下测试内容:
//引入mockjs import Mock from 'mockjs' //使用mockjs模拟数据 Mock.mock('/test', { "res": 0, "data": { "datatime": "@datetime",//随机生成日期时间 "weekday|1-7": 7,//随机生成1-7的数字 "name": "@cname",//随机生成中文名字 } });
在main.js引入此mock.js就可以进行全局拦截axios和ajax的请求了。
import './mock/index.js';
二、数据请求
1、get请求
在之前的Main1页面上编写代码
创建按钮
get数据
创建axios请求方法
export default { name: "Main1", methods: { getTest() { this.$axios.get("/test").then((res) => { console.log(res.data); }); }, }, };
this.$axios.get(“/test”)中this.$axios.get 表示使用get请求,“/test” 访问路径,刚好与之前mock.js定义的想吻合;
res 就是取得返回的数据集合,其中res.data就是我们定义好的返回数据。
浏览器中“右键-检查”或“F12”
2、post请求
添加post请求按钮
post测试1
编写js post代码
postTest(){ this.$axios.post("/post/test1",{id:1}).then(res=>{ console.log(res.data) }) }
在mock/index.js其中第2个参数指定为 post,如果我们用get请求则会提示404,只能用post
Mock.mock('/post/test1', 'post', function (param) { console.log('传入的参数为:', param.body) return { res: 1, msg: "success" } });
效果展示
3、添加数据
按钮代码
add数据
请求方法代码
postAdd(){ this.$axios.post("/post/add",{id:1,name:'哈哈'}).then(res=>{ console.log(res.data) }) }
Mockjs数据
// 定义userList数组 let userList = []; Mock.mock('/post/add', 'post', function (param) { let body = JSON.parse(param.body) // 获取请求参数 let id = parseInt(body.id) let flag = true for (let item of userList) { if (item.id === id) flag = false // 判断id是否已经存在 } // 如果id不存在 if (flag) { userList.push( { name: body.name, id } ) return { userList, res: 0, msg: '添加成功' } } else { return { userList, res: 1, msg: '添加失败' } } });
效果展示
第一次发送请求,因为里面没有id为1的数据,所以添加成功
第二次发送请求,因为id=1的数据已经添加成功了,所以失败
重新换一个id就可以添加成功
4、修改
按钮代码
mod数据
请求代码
postMod(){ this.$axios.post("/post/mod",{name:'哈哈',id:3}).then(res=>{ console.log(res.data) }) }
mockjs数据
Mock.mock('/post/mod', 'post', function (param) { let body = JSON.parse(param.body) // 获取请求参数 let id = parseInt(body.id) let flag = false, index = 0; for (let i in userList) { if (userList[i].id === id) { flag = true // 判断id是否已经存在,存在返回true index = i//对应数组的下标 } } // 如果id存在则修改 if (flag) { userList[index] = body return { userList, res: 0, msg: '修改成功' } } else { return { userList, res: 1, msg: '修改失败' } } });
效果展示
因为第一次修改里面没有数据,所以修改失败
先点击 添加add,再点击 修改mod
5、删除
按钮代码
del数据
请求代码
postDel() { this.$axios.post("/post/del", { id: 1 }).then((res) => { console.log(res.data); }); },
mockjs数据
Mock.mock('/post/del', 'post', function (param) { let body = JSON.parse(param.body) // 获取请求参数 let id = parseInt(body.id) let flag = false, index = 0; for (let i in userList) { if (userList[i].id === id) { flag = true // 判断id是否已经存在,存在返回true index = i//对应数组的下标 } } // 如果id存在则删除 if (flag) { userList.splice(index, 1); return { userList, res: 0, msg: '删除成功' } } else { return { userList, res: 1, msg: '删除失败' } } });
效果展示
先添加数据,再删除数据
6、查询
按钮代码
query无参数据
query有参数据请求代码,分别是没有参数的查询全部,有id参数的根据id来查询
(1)无参查询
postQuery(){ this.$axios.post("/post/query",{}).then(res=>{ console.log(res.data) }) }
(2)有参查询
postQuery2(){ this.$axios.post("/post/query",{id:1}).then(res=>{ console.log(res.data) }) }
mockjs数据
Mock.mock('/post/query', 'post', function (param) { let body = JSON.parse(param.body) // 获取请求参数 let id = parseInt(body.id) if (!id) {//如果id不存在,则直接返回全部 return { userList, res: 0, msg: '查询成功' } } //id for (let item of userList) { if (item.id === id) { return { userList: [item], res: 0, msg: '查询成功' } } } // 如果id不存在则返回失败 return { userList: [], res: 1, msg: '查询失败' } });
效果展示
按照图示步骤执行
- 首先进行无参查询,查询全部,返回是空
- 其次是添加一条数据
- 接着带参查询id=1的数据
到此为止,增删改查,get、post都已测试完成,put等方法自己进行测试
附全部代码,如下:
Main1.vue
这是Main1
get数据
post测试1
add数据
mod数据
del数据
query无参数据
query有参数据
export default { name: "Main1", data() { return { userList: [{ id: 1, name: "张三" }], }; }, methods: { getTest() { this.$axios.get("/test").then((res) => { console.log(res.data); }); }, postTest() { this.$axios.post("/post/test1", { id: 1 }).then((res) => { console.log(res.data); }); }, postAdd() { this.$axios.post("/post/add", { id: 1, name: "牛牛" }).then((res) => { console.log(res.data); }); }, postMod() { this.$axios.post("/post/mod", { name: "哈哈", id: 3 }).then((res) => { console.log(res.data); }); }, postDel() { this.$axios.post("/post/del", { id: 3 }).then((res) => { console.log(res.data); }); }, postQuery() { this.$axios.post("/post/query", {}).then((res) => { console.log(res.data); }); }, postQuery2() { this.$axios.post("/post/query", { id: 1 }).then((res) => { console.log(res.data); }); }, }, }; .el-button { height: auto; }mock/index.js
//引入mockjs import Mock from 'mockjs' //使用mockjs模拟数据 Mock.mock('/test', { "res": 0, "data": { "datatime": "@datetime",//随机生成日期时间 "weekday|1-7": 7,//随机生成1-7的数字 "name": "@cname",//随机生成中文名字 } }); Mock.mock('/post/test1', 'post', function (param) { console.log('传入的参数为:', param.body) return { res: 1, msg: "success" } }); // 定义userList数组 let userList = []; Mock.mock('/post/add', 'post', function (param) { let body = JSON.parse(param.body) // 获取请求参数 let id = parseInt(body.id) let flag = true for (let item of userList) { if (item.id === id) flag = false // 判断id是否已经存在 } // 如果id不存在 if (flag) { userList.push( { name: body.name, id } ) return { userList, res: 0, msg: '添加成功' } } else { return { userList, res: 1, msg: '添加失败' } } }); Mock.mock('/post/mod', 'post', function (param) { let body = JSON.parse(param.body) // 获取请求参数 let id = parseInt(body.id) let flag = false, index = 0; for (let i in userList) { if (userList[i].id === id) { flag = true // 判断id是否已经存在,存在返回true index = i//对应数组的下标 } } // 如果id存在则修改 if (flag) { userList[index] = body return { userList, res: 0, msg: '修改成功' } } else { return { userList, res: 1, msg: '修改失败' } } }); Mock.mock('/post/del', 'post', function (param) { let body = JSON.parse(param.body) // 获取请求参数 let id = parseInt(body.id) let flag = false, index = 0; for (let i in userList) { if (userList[i].id === id) { flag = true // 判断id是否已经存在,存在返回true index = i//对应数组的下标 } } // 如果id存在则删除 if (flag) { userList.splice(index, 1); return { userList, res: 0, msg: '删除成功' } } else { return { userList, res: 1, msg: '删除失败' } } }); Mock.mock('/post/query', 'post', function (param) { let body = JSON.parse(param.body) // 获取请求参数 let id = parseInt(body.id) if (!id) {//如果id不存在,则直接返回全部 return { userList, res: 0, msg: '查询成功' } } //id for (let item of userList) { if (item.id === id) { return { userList: [item], res: 0, msg: '查询成功' } } } // 如果id不存在则返回失败 return { userList: [], res: 1, msg: '查询失败' } });
Aside/index.vue
{{ item.name }} export default { name: "Aside", data() { return { menu_data: [ { name: "一级菜单1", icon: "el-icon-location", path: "/index/menu1", }, { name: "一级菜单2", icon: "el-icon-document", path: "/index/menu2", }, { name: "一级菜单3", icon: "el-icon-setting", path: "/index/menu3", }, ], }; }, }; .el-icon-location, .el-icon-document, .el-icon-setting { display: inline-flex; align-items: center; justify-content: center; }