vue-ajax
vue 项目中常用的 2 个 ajax 库
在Vue项目中前后端交互时,早期的Vue版本使用Vue-resource插件从后台获取数据。从Vue2.0之后就不再对vue-resource进行更新,而是推荐使用axios.
vue-resource
Vue.js的插件提供了使用XMLHttpRequest 或 JSONP进行Web请求和处理响应的服务。vue-resource像jQuery的$.ajax,用来进行数据交互。主要用于发送ajax请求。
特点:
1.体积小,压缩后大约12kb
2.支持主流浏览器,除了IE9以下
3.支持Promiss API 和URL Templates
4.支持拦截器,拦截器是全局的,可以在请求发送前和发送请求后做一些事情。
axios
通用的 ajax 请求库, 官方推荐, vue2.x 使用广泛
特点:
1.在浏览器中发送XMLHttpRequests请求
2.在node.js中发送http请求
3.支持Promiss API
4.拦截器请求和响应
5.转换请求和响应数据
6.取消请求
7.自动转换JSON数据
8.客户端支持保护安全免受CSRF/XSRF攻击
vue-resource 的使用
在线文档
https://github.com/pagekit/vue-resource/blob/develop/docs/http.md
下载
npm install vue-resource --save
编码
// 引入模块
import VueResource from 'vue-resource'
// 使用插件
Vue.use(VueResource) // 执行完成之后,会给vue实例和组件对象添加$http属性
// 通过 vue/组件对象发送 ajax 请求
this.$http.get('/someUrl').then((response) => {
// success callback
console.log(response.data) //返回结果数据
}, (response) => {
// error callback
console.log(response.statusText) //错误信息
})
axios 的使用
特性
- 从浏览器中创建 XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求数据和响应数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持防御
在线文档
https://github.com/pagekit/vue-resource/blob/develop/docs/http.md
安装
使用 npm:
npm install axios --save
使用 cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
直接引入本地文件
编码
// 引入模块
import axios from 'axios'
// 发送 ajax 请求
axios.get(url)
.then(response => {
console.log(response.data) // 得到返回结果数据
})
.catch(error => {
console.log(error.message)
})
测试接口
接口 1: https://api.github.com/search/repositories?q=v&sort=stars
接口 2: https://api.github.com/search/users?q=aa
组件发送ajax请求案例
入口main.js
/* 入口js文件,需要在这里面创建vue实例 */
import Vue from 'vue'
import VueResource from 'vue-resource'
import App from './App'
// 使用插件
Vue.use(VueResource) // 内部会给vm对象和组件对象添加一个属性: $http;里面有get()和post()等方法
/* eslint-disable no-new */
new Vue({
// 挂载在index.html的#app元素上
el: '#app',
components: {
App
},
template: '<App/>'
})
App组件编码
<template>
<div>
<div v-if="!repoUrl">加载中...</div>
<div v-else>
最受欢迎的仓库是: <a :href="repoUrl">{{ repoName }}</a>
</div>
</div>
</template>
<script>
// 引入模块
import axios from "axios";
export default {
data() {
return {
repoUrl: "",
repoName: "",
};
},
methods: {},
mounted() {
// 发送ajax请求获取数据
const url = "https://api.github.com/search/repositories?q=vu&sort=stars";
// vue-resource发送ajax请求
this.$http.get(url).then(
(response) => {
// success callback
// console.log(response.data); //返回结果数据
const result = response.data;
const mostRepo = result.items[0];
this.repoUrl = mostRepo.html_url;
this.repoName = mostRepo.name;
},
(response) => {
// error callback
console.log("请求失败"); //错误信息
}
);
// 使用axios发送ajax请求
axios
.get(url)
.then((response) => {
const result = response.data;
const mostRepo = result.items[0];
this.repoUrl = mostRepo.html_url;
this.repoName = mostRepo.name;
})
.catch((error) => {
console.log("请求失败"); //错误信息
});
},
};
</script>
<style>
</style>
非组件发送ajax请求案例
定义json-server数据
{
"phone": [
{
"id": 1,
"pro_name": "小米",
"price": "1888",
"store_count": "2000"
},
{
"id": 2,
"pro_name": "华为",
"price": "2888",
"store_count": "210"
}
]
}
axios发送请求
引入axios
<script src="js/axios.js"></script>
编写html模板
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<!-- 引入vue.js -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<style>
html,
body,
h1 {
margin: 0;
padding: 0;
}
.header {
background-color: #1b6d85;
height: 80px;
margin: 0px;
}
.container {
display: flex;
height: 600px;
}
.left {
background-color: #3c763d;
flex: 2;
}
.main {
background-color: #5bc0de;
flex: 8;
}
</style>
</head>
<body>
<div id="root">
<input type="text" placeholder="商品名称" id="pro_name" v-model="pro_name">
<input type="text" placeholder="商品价格" id="price" v-model="price">
<input type="text" placeholder="商品名称" id="store_count" v-model="store_count">
<button v-on:click="getReq">get请求数据</button>
<button v-on:click="postReq">post请求数据</button>
<h3>{{site_name}}</h3>
<ul>
<li v-for="(item,index) of pro_list" :key="item.id">
<h3>{{item.pro_name}}</h3>
<p>价格是:{{item.price}},库存剩余:{{item.store_count}}</p>
</li>
</ul>
</div>
<script>
var VM = new Vue({
el: "#root",
data: {
site_name: "手机专区",
pro_name: "",
price: "",
store_count: "",
pro_list: []
},
methods: {
getReq() {
//get请求
axios({
methods: 'get',
url: 'http://localhost:3000/phone'
}).then((Response) => {
console.log(Response.data)
console.log(Response.data[0].pro_name)
this.pro_list = Response.data
}).catch((err) => {
console.log(err)
})
},
postReq() {
//post请求
axios.post('http://localhost:3000/phone', {
pro_name: this.pro_name,
price: this.price,
store_count: this.store_count
}).then((Response) => {
this.pro_list.push(Response.data);
}).catch((error) => {
console.log(error)
})
}
}
})
</script>
</body>
</html>