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页面上编写代码
创建按钮
<el-button @click="getTest">get数据</el-button>
创建axios请求方法
<script>
export default {name: "Main1",methods: {getTest() {this.$axios.get("/test").then((res) => {console.log(res.data);});},},
};
</script>
this.$axios.get(“/test”)中this.$axios.get表示使用get请求,“/test” 访问路径,刚好与之前mock.js定义的想吻合;
res 就是取得返回的数据集合,其中res.data就是我们定义好的返回数据。
浏览器中“右键-检查”或“F12”

2、post请求
添加post请求按钮
<el-button @click="postTest">post测试1</el-button>
编写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、添加数据
按钮代码
<el-button @click="postAdd">add数据</el-button>
请求方法代码
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 = truefor (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、修改
按钮代码
<el-button @click="postMod">mod数据</el-button>
请求代码
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是否已经存在,存在返回trueindex = i//对应数组的下标}}// 如果id存在则修改if (flag) {userList[index] = bodyreturn {userList,res: 0,msg: '修改成功'}} else {return {userList,res: 1,msg: '修改失败'}}
});
效果展示
因为第一次修改里面没有数据,所以修改失败
先点击 添加add,再点击 修改mod

5、删除
按钮代码
<el-button @click="postDel">del数据</el-button>
请求代码
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是否已经存在,存在返回trueindex = i//对应数组的下标}}// 如果id存在则删除if (flag) {userList.splice(index, 1);return {userList,res: 0,msg: '删除成功'}} else {return {userList,res: 1,msg: '删除失败'}}
});
效果展示
先添加数据,再删除数据

6、查询
按钮代码
<el-button @click="postQuery">query无参数据</el-button><br /><br />
<el-button @click="postQuery2">query有参数据</el-button><br /><br />
请求代码,分别是没有参数的查询全部,有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: '查询成功'}}//idfor (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
<template><div><span>这是Main1</span><br /><br /><el-button @click="getTest">get数据</el-button><br /><br /><el-button @click="postTest">post测试1</el-button><br /><br /><el-button @click="postAdd">add数据</el-button><br /><br /><el-button @click="postMod">mod数据</el-button><br /><br /><el-button @click="postDel">del数据</el-button><br /><br /><el-button @click="postQuery">query无参数据</el-button><br /><br /><el-button @click="postQuery2">query有参数据</el-button><br /><br /></div>
</template><script>
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);});},},
};
</script><style scoped>
.el-button {height: auto;
}
</style>
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 = truefor (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是否已经存在,存在返回trueindex = i//对应数组的下标}}// 如果id存在则修改if (flag) {userList[index] = bodyreturn {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是否已经存在,存在返回trueindex = 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: '查询成功'}}//idfor (let item of userList) {if (item.id === id) {return {userList: [item],res: 0,msg: '查询成功'}}}// 如果id不存在则返回失败return {userList: [],res: 1,msg: '查询失败'}
});
Aside/index.vue
<template><div style="height: 100%"><el-menubackground-color="#545c64"text-color="#ffffff"active-text-color="#ffd04b"class="el-menu-vertical-demo"router><el-menu-item:index="item.path"v-for="item in menu_data":key="item.name"><i :class="item.icon"></i>{{ item.name }}</el-menu-item></el-menu></div>
</template><script>
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",},],};},
};
</script><style scoped>
.el-icon-location,
.el-icon-document,
.el-icon-setting {display: inline-flex;align-items: center;justify-content: center;
}
</style>相关文章:
Vue开发实例(七)Axios的安装与使用
说明: 如果只是在前端,axios常常需要结合mockjs使用,如果是前后端分离,就需要调用对应的接口,获取参数,传递参数;由于此文章只涉及前端,所以我们需要结合mockjs使用;由于…...
2024.3.6
作业1:使用C语言完成数据库的增删改 #include <myhead.h>//定义添加员工信息函数 int Add_worker(sqlite3 *ppDb) {//准备sql语句printf("请输入要添加的员工信息:\n");//从终端获取员工信息char rbuf[128]"";fgets(rbuf,sizeof(rbuf),s…...
抖音视频批量采集软件|视频评论下载工具
在日常工作中,需要频繁下载抖音视频,但逐个复制分享链接下载效率太低?别担心!我们推出了一款专业的抖音视频批量采集软件,基于C#开发,满足您的需求,让您通过关键词搜索视频并自动批量抓取&#…...
苹果 Vision Pro零售部件成本价格分析
苹果公司发布的全新头戴式显示器 Apple Vision Pro 虽然售价高达3499美元,但其制造成本同样不菲,根据研究机构 Omdia 的估计,该头显仅零部件成本就超过了1500美元。这款头显的总零部件成本估计为1542美元,这还并不包括研发、包装、…...
Seurat 中的数据可视化方法
本文[1]将使用从 2,700 PBMC 教程计算的 Seurat 对象来演示 Seurat 中的可视化技术。您可以从 SeuratData[2] 下载此数据集。 SeuratData::InstallData("pbmc3k")library(Seurat)library(SeuratData)library(ggplot2)library(patchwork)pbmc3k.final <- LoadData(…...
ImportError: cannot import name ‘InterpolationMode‘
InterpolationMode 在图像处理库中通常用于指定图像缩放时的插值方法。插值是一种数学方法,在图像大小变化时用于估算新像素位置的像素值。不同的插值方法会影响缩放后图像的质量和外观。 在你提供的 image_transform 函数中,InterpolationMode.BICUBIC…...
HSRP和VRRP
VRRP(Virtual Router Redundancy Protocol,虚拟路由器冗余协议) 是一种网络层的容错协议,主要用于在多台路由器之间提供默认网关冗余。在IP网络中,当一个子网有多个路由器时,VRRP可以确保在主用路由器失效…...
C及C++每日练习(1)
一.选择: 1.以下for循环的执行次数是() for(int x 0, y 0; (y 123) && (x < 4); x); A.是无限循环 B.循环次数不定 C.4次 D.3次 对于循环,其组成部分可以四个部分: for(初始化;循环进行条件;调整) …...
Oracle 12c dataguard查看主备库同步情况的新变化
导读 本文介绍Oracle 12c dataguard在维护方面的新变化 前提:主库备库的同步是正常的。 1、主库上查看archive Log list SYScdb1> archive log list; Database log mode Archive Mode Automatic archival Enabled Archive destination…...
时间序列-AR MA ARIMA
一、AR模型(自回归) AR探索趋势和周期性 预测依赖于过去的观测值和模型中的参数。模型的阶数 p pp 决定了需要考虑多少个过去时间点的观测值。 求AR模型的阶数 p和参数 ϕ i \phi_i ϕi ,常常会使用统计方法如最小二乘法、信息准则(如AIC、BIC…...
Spring Boot(六十六):集成Alibaba Druid 连接池
1 Alibaba Druid介绍 在现代的Java应用中,使用一个高效可靠的数据源是至关重要的。Druid连接池作为一款强大的数据库连接池,提供了丰富的监控和管理功能,成为很多Java项目的首选。本文将详细介绍如何在Spring Boot项目中配置数据源,集成Druid连接池,以实现更高效的数据库…...
leetcode 经典题目42.接雨水
链接:https://leetcode.cn/problems/trapping-rain-water 题目描述 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。 思路分析 首先,我们需要遍历数组,对于每个元素&am…...
高防服务器的主要作用有哪些?
高防服务器是属于服务器的一种,主要是为了解决流量攻击而设计的,高防服务器能够维护服务器的稳定性和安全性,具备很高的防御能力和更加优质的网络带宽,能够提供更加可靠的服务保障,那么高防服务器主要都有哪些作用呢&a…...
【30 天 JavaScript 挑战】学习笔记
30 天 JavaScript 挑战 专为 JavaScript 初学者设计 掌握必备 JavaScript 技能 前端人,前端魂,刷完 JS 即入门! 题目地址:https://leetcode.cn/studyplan/30-days-of-javascript/ 个人学习笔记:https://github.com/kaimo313/…...
生成 Linux/ubuntu/Debian 上已安装软件包的列表
你可以在终端中使用以下命令生成已安装软件包的列表: 列出所有已安装的软件包: dpkg --get-selections要将列表保存到文件中: dpkg -l > installed_packages_detailed.txt这将在当前目录中创建一个名为“installed_packages_detailed.txt”…...
精品中国货出海wordpress外贸独立站建站模板
旗袍唐装wordpress外贸网站模板 旗袍、唐装、华服wordpress外贸网站模板,适合做衣服生意的外贸公司官网使用。 https://www.jianzhanpress.com/?p3695 劳动防护wordpress外贸独立站模板 劳动防护wordpress外贸独立站模板,劳动保护、劳动防护用品外贸…...
使用Animated.View实现全屏页面可以向下拖动,松开手指页面返回原处的效果
使用Animated.View实现全屏页面可以向下拖动,松开手指页面返回原处的效果 效果示例图代码示例 效果示例图 代码示例 import React, {useRef, useState} from react; import {View,Text,Animated,Easing,PanResponder,StyleSheet, } from react-native;const TestDragCard () …...
【教程】uni-app iOS打包解决profile文件与私钥证书不匹配问题
摘要 当在uni-app中进行iOS打包时,有时会遇到profile文件与私钥证书不匹配的问题。本文将介绍如何解决这一问题,以及相关的技术细节和操作步骤。 引言 在uni-app开发过程中,iOS打包是一个常见的操作。然而,有时会出现profile文…...
预约自习室
预约自习室 1、技术介绍 自习室预约系统的后端开发语言采用Node,后端开发框架采用Express,数据库采用的Node的最佳搭档MySQL。采用Vue作为前端开发框架,Element-UI作为开发的组件库,微信小程序。期间采用axios实现网页数据获取&a…...
网络安全审计是什么意思?与等保测评有什么区别?
网络安全审计和等保测评在信息安全领域中都是非常重要的环节。但不少人对于这两者是傻傻分不清楚,今天我们就来简单聊聊网络安全审计是什么意思?与等保测评有什么区别? 网络安全审计是什么意思? 网络安全审计是通过对网络系统和网…...
C++实现分布式网络通信框架RPC(3)--rpc调用端
目录 一、前言 二、UserServiceRpc_Stub 三、 CallMethod方法的重写 头文件 实现 四、rpc调用端的调用 实现 五、 google::protobuf::RpcController *controller 头文件 实现 六、总结 一、前言 在前边的文章中,我们已经大致实现了rpc服务端的各项功能代…...
Prompt Tuning、P-Tuning、Prefix Tuning的区别
一、Prompt Tuning、P-Tuning、Prefix Tuning的区别 1. Prompt Tuning(提示调优) 核心思想:固定预训练模型参数,仅学习额外的连续提示向量(通常是嵌入层的一部分)。实现方式:在输入文本前添加可训练的连续向量(软提示),模型只更新这些提示参数。优势:参数量少(仅提…...
【Java学习笔记】Arrays类
Arrays 类 1. 导入包:import java.util.Arrays 2. 常用方法一览表 方法描述Arrays.toString()返回数组的字符串形式Arrays.sort()排序(自然排序和定制排序)Arrays.binarySearch()通过二分搜索法进行查找(前提:数组是…...
Redis数据倾斜问题解决
Redis 数据倾斜问题解析与解决方案 什么是 Redis 数据倾斜 Redis 数据倾斜指的是在 Redis 集群中,部分节点存储的数据量或访问量远高于其他节点,导致这些节点负载过高,影响整体性能。 数据倾斜的主要表现 部分节点内存使用率远高于其他节…...
Spring AI与Spring Modulith核心技术解析
Spring AI核心架构解析 Spring AI(https://spring.io/projects/spring-ai)作为Spring生态中的AI集成框架,其核心设计理念是通过模块化架构降低AI应用的开发复杂度。与Python生态中的LangChain/LlamaIndex等工具类似,但特别为多语…...
docker 部署发现spring.profiles.active 问题
报错: org.springframework.boot.context.config.InvalidConfigDataPropertyException: Property spring.profiles.active imported from location class path resource [application-test.yml] is invalid in a profile specific resource [origin: class path re…...
Python 实现 Web 静态服务器(HTTP 协议)
目录 一、在本地启动 HTTP 服务器1. Windows 下安装 node.js1)下载安装包2)配置环境变量3)安装镜像4)node.js 的常用命令 2. 安装 http-server 服务3. 使用 http-server 开启服务1)使用 http-server2)详解 …...
论文阅读:LLM4Drive: A Survey of Large Language Models for Autonomous Driving
地址:LLM4Drive: A Survey of Large Language Models for Autonomous Driving 摘要翻译 自动驾驶技术作为推动交通和城市出行变革的催化剂,正从基于规则的系统向数据驱动策略转变。传统的模块化系统受限于级联模块间的累积误差和缺乏灵活性的预设规则。…...
[拓扑优化] 1.概述
常见的拓扑优化方法有:均匀化法、变密度法、渐进结构优化法、水平集法、移动可变形组件法等。 常见的数值计算方法有:有限元法、有限差分法、边界元法、离散元法、无网格法、扩展有限元法、等几何分析等。 将上述数值计算方法与拓扑优化方法结合&#…...
游戏开发中常见的战斗数值英文缩写对照表
游戏开发中常见的战斗数值英文缩写对照表 基础属性(Basic Attributes) 缩写英文全称中文释义常见使用场景HPHit Points / Health Points生命值角色生存状态MPMana Points / Magic Points魔法值技能释放资源SPStamina Points体力值动作消耗资源APAction…...


