vue 三、Axios (ajax 框架) 在vue 项目中的使用
前篇:ajax 与 axios的区别
刚刚接触axios有好多疑惑。它和ajax有什么关系呢和区别呢?接下来一起看下:
1.区别
axios是通过promise实现对ajax技术的一种封装,就像jQuery实现ajax封装一样。
简单来说: ajax技术实现了网页的局部数据刷新,axios实现了对ajax的封装。
axios是ajax ajax不止axios。
下面列出代码来对比一下:
axios:
axios({url: '/getUsers',method: 'get',responseType: 'json', // 默认的data: {//'a': 1,//'b': 2,}}).then(function (response) {console.log(response);console.log(response.data);}).catch(function (error) {console.log(error);})
JQuery- ajax:
$.ajax({url: '/getUsers',type: 'get',dataType: 'json',data: {//'a': 1,//'b': 2,},success: function (response) {console.log(response);}})
2.优缺点:
ajax:
本身是针对MVC的编程,不符合现在前端MVVM的浪潮
基于原生的XHR开发,XHR本身的架构不清晰,已经有了fetch的替代方案
JQuery整个项目太大,单纯使用ajax却要引入整个JQuery非常的不合理(采取个性化打包的方案又不能享受CDN服务
axios:
从 node.js 创建 http 请求
支持 Promise API
客户端支持防止CSRF
提供了一些并发请求的接口(重要,方便了很多的操作)
一、安装Axios 依赖
使用 npm: $ npm install axios || npm i axios使用 bower: $ bower install axios使用 cdn: <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
当前使用命令(在项目目录下执行)
npm i axios
二、模拟数据(使用java创建测试接口模拟数据)
测试接口
查询所有: http://localhost:8088/findAll
id查询:http://localhost:8088/findId ?id=1
添加:http://localhost:8088/insert ?id=1&name=wang&age=22
修改:http://localhost:8088/update ?id=1&name=erping&age=24
Uncaught (in promise) Error: Request failed with status code 400 错误说明
axios请求如果出现: **Uncaught (in promise) Error: Request failed with status code 400** 错误
那么请注意 axios请求头的 Content-Type 默认是 application/json,后台接收格式也要为 application/json,
此处使用了@RequestBody 处理,postman 工具默认的是 application/x-www-form-urlencoded
此次的跨域问题后台处理方式,使用springboot 的跨域处理注解
@CrossOrigin(origins = "*", allowCredentials = "true")
示例代码如下:看不懂的请跳过
/*** TODO 用户管理** @author 王松* @mail 1720696548@qq.com* @date 2020/1/28 0028 11:29*/
@RestController
public class UserService {//user数据容器,key=idprivate static List<User> users = new ArrayList<>();/*** TODO 查询所有*/@GetMapping("findAll")@CrossOrigin(origins = "*", allowCredentials = "true")public String getAll() {if (users.size() <= 0) {return "查询成功,用户信息为空";} else {return users.toString();}}/*** TODO id查询*/@GetMapping("/findId")@CrossOrigin(origins = "*", allowCredentials = "true")public String get(int id) {User user = this.getId(id);if (user == null) {return "没有该id数据";} else {return user.toString();}}/*** TODO 查询用户信息** @param user 参数[id,name,age]*/@RequestMapping("/insert")@CrossOrigin(origins = "*", allowCredentials = "true")public String insert(@RequestBody User user) {users.add(user);return "添加成功";}/*** TODO 修改用户信息** @param user 参数[id,name,age] -- id必传*/@RequestMapping("/update")@CrossOrigin(origins = "*", allowCredentials = "true")public String update(@RequestBody User user) {//删除原数据for (User oldUser : users) {if (oldUser.getId() == user.getId()) {users.remove(oldUser);break;}}//添加users.add(user);return "修改成功";}//通过id 获取用户信息private User getId(Integer id) {for (User user : users) {if (user.getId() == id) {return user;}}return null;}
三、Vue 项目使用Axios
1、main.js 加载axios组件
// 导入axios //安装命令 npm i axios
import axios from 'axios'; // 注册到全局组件
Vue.use(axios); //axios 相关配置,注意:axios请求头的 Content-Type 默认是 application/json,而postman默认的是 application/x-www-form-urlencoded
var instance = axios.create({//请求根目录baseURL: 'http://localhost:8088', // withCredentials : true,//timeout: 1000,// headers: {'X-Custom-Header': 'foobar'},
});Vue.prototype.$axios = instance; // 使用方式 this.$axios
2、get 请求示例
this.$axios.get('/findId?id=1').then(function(response) {//请求成功window.console.log(response);_this.resUser = response.data;}).catch(function(err) {alert("请求失败--" + err)});
3、post 请求示例
this.$axios.post('/insert', {id: _this.addUser.id,name: _this.addUser.name,age: _this.addUser.age,}).then(function(response) {//请求成功alert("请求成功--" + response.data);}).catch(function(err) {//请求失败alert("请求失败--" + err)});
4、 AxiosTest.vue(测试get,post 代码)
let _this = this; 注意this 作用域范围,需要重新定义变量接收
<template><div><button @click="findAll"> 查询所有(GET)</button><button @click="findId1"> id查询1(GET-id=1)</button><button @click="findId2"> id查询2(GET-id=2)</button><hr />users = {{resUser}} <!-- 展示查询数据 --><hr /><input type="text" v-model="addUser.id" /><input type="text" v-model="addUser.name" /><input type="text" v-model="addUser.age" /><button @click="insert"> 添加</button><br /><input type="text" v-model="updUser.id" /><input type="text" v-model="updUser.name" /><input type="text" v-model="updUser.age" /><button @click="update"> 修改</button></div>
</template><script type="text/javascript">export default {//定义当前vue数据,每个实例数据是独立的data() {return {resUser: {}, //查询数据addUser: {"id": 1, name: "wangsong", age: 22}, //添加输入框数据updUser: {"id": 1, name: "erping", age: 23}, //修改输入框数据}},methods: {// 查询所有findAll() {let _this = this;this.$axios.get('/findAll').then(function(response) {//请求成功window.console.log(response);//赋值属性_this.resUser = response.data;}).catch(function(err) {alert("请求失败--" + err)});},// id查询方式一,url 拼接查询参数findId1() {let _this = this;//通过给定的ID来发送请求//this.$axios.get('/user?ID=12345')this.$axios.get('/findId?id=1').then(function(response) {//请求成功window.console.log(response);_this.resUser = response.data;}).catch(function(err) {alert("请求失败--" + err)});},// id查询方式二,params 添加查询参数findId2() {let _this = this;//以上请求也可以通过这种方式来发送this.$axios.get('/findId', {//请求参数params: {id: 2}}).then(function(response) {//请求成功window.console.log(response);_this.resUser = response.data;}).catch(function(err) {//请求失败alert("请求失败--" + err)});},//添加insert() {const _this = this;//以上请求也可以通过这种方式来发送this.$axios.post('/insert', {id: _this.addUser.id,name: _this.addUser.name,age: _this.addUser.age,}).then(function(response) {//请求成功alert("请求成功--" + response.data);}).catch(function(err) {//请求失败alert("请求失败--" + err)});},//修改update() {const _this = this;//以上请求也可以通过这种方式来发送this.$axios.post('/update', {id: _this.updUser.id,name: _this.updUser.name,age: _this.updUser.age,}).then(function(response) {//请求成功alert("请求成功--" + response.data);}).catch(function(err) {//请求失败alert("请求失败--" + err)});}}}
</script><style>
</style>
5、测试效果
测试页
添加数据
查询数据
修改数据
查询所有
其他还有一些可以参考地址:https://www.kancloud.cn/yunye/axios/234845
如:url 拦截器(可以进行 toket验证),合并请求(两个请求需同时发送),还有请求配置等等
vue 三、Axios (ajax 框架) 在vue 项目中的使用相关推荐
- vue三种ajax请求方式,vue请求数据的三种方式
请求数据的方式: vue-resource 官方提供的 vue的一个插件 axios fetch-jsonp 一,vue-resource请求数据 介绍:vue-resource请求数据方式是官方提供 ...
- Vue之Axios AJAX封装
来源:我的博客站 OceanicKang |<Vue 之 Axios AJAX封装> 前言 才不要写前言,Axios 中文文档 https://www.kancloud.cn/yunye/ ...
- Quartz-2.2.1 任务调度框架在Java项目中的使用实例
< Quartz-2.2.1 任务调度框架在Java项目中的使用实例 > 本实例是基于Quartz 2.2.1 版本为中心,也是目前最新的Quartz任务调度框架. 目前在 J2EE 项目 ...
- 17、基于Mybaits、Vue、axios、Element-ui的JavaWeb项目
目录 1.项目功能介绍 编辑 2.环境准备 创建项目 准备数据库 准备Mybatis核心配置文件 创建实体类与Mapper映射文件 补全项目结构 1.在pom.xml中导入相关依赖 2.导入axio ...
- vue php axios 跨域,在vue项目中,使用axios跨域处理
下面我就为大家分享一篇在vue项目中,使用axios跨域处理,具有很好的参考价值,希望对大家有所帮助. 跨域,一个很是让人尴尬的问题,有些人可以在后台中设置请求头,但是很多前端并不具备后台的知识,并无 ...
- Vue使用Axios Ajax封装渲染页面
接口文档 约定: baseURL: http://127.0.0.1:9999 返回参数: {"code": 1, "msg":"新增数据失败!&qu ...
- vue赋值与ajax什么区别,Vue中ajax返回的结果赋值
这是第二次在项目中遇到此问题,ajax请求成功后在success函数中为Vue实例data里的变量赋值,却失败了 new Vue({ el:'#app', data:{ msg:'' }, creat ...
- vue怎么vw布局好用_Vue项目中使用vw实现移动端适配-阿里云开发者社区
我们在vue移动端项目中的适配一般都采用rem,但是rem也不是能兼容所有的终端. 随着viewport单位越来越受到众多浏览器的支持,下面将简单介绍怎么实现vw的兼容问题,用vw代替rem 当我们采 ...
- 二、Vue(发送AJAX请求、Vue生命周期、计算属性、属性和方法、自定义指令、过渡(动画))
一. 发送AJAX请求 1. 简介 vue本身不支持发送AJAX请求,需要使用vue-resource.axios等插件实现 axios是一个基于Promise的HTTP请求客户端,用 ...
最新文章
- 20190226-利用序列化完成小型记账程序
- 突然开掉CEO!通用电气时隔一年再换帅,金融和工业互联网都救不了GE?
- JavaScript 如何使用闭包
- python培训班有用吗-Python培训班哪家好?
- 利用Nginx轻松实现Ajax的跨域请求(前后端分离开发调试必备神技)
- python优先级排序_python中使用优先队列
- 电子信息工程这个专业学的是什么内容,就业怎么样?
- Vue3中的父子、子父组件通信
- 会议OA项目之我的审批(查询会议签字)
- OpenDDS典型idl举例(系统)
- oppo手机android 版本号,OPPO R11有几个版本?OPPO R11各版本区别对比详细评测
- 带有打开密码的压缩包如何解压
- 第四方聚合支付服务的前景
- NetWorkHelper 检测网络状态
- Struts 官方下载地址
- ubuntu 改屏幕分辨率命令_ubuntu 修改分辨率为自定义分辨率
- 吐血推荐珍藏的Visual Studio Code插件
- spring 的 applicationcontext.xml
- 企业邮箱注册申请,如何注册电子邮箱域名
- oracle sql 字段值行 连乘,如何使用Oracle数据库将矩阵与其转置相乘,并使用utl_nla...
热门文章
- java中public static_对java中public、static的理解
- html编码有问题,html特殊字符编码问题导致的细节问题
- coreelec 下载app_DY的瞎折腾系列 篇十五:N1多媒体系统CoreELEC 百度云下载指南...
- 淘宝API图片尺寸的缩略图解决办法
- GCE 部署 ELK 7.1可视化分析 nginx
- sha1sum command
- (六十七)神经网络——MLP
- Python 机器人魔鬼的步伐中居然隐藏着杨辉三角形
- linux tftp客户端安装命令,Linux系统中tftp命令使用详解
- scala中的implicit