vue_resource和axios

vue_resource和axios

1. 简介

vue本身不支持发送AJAX请求,需要使用vue-resource、axios等插件实现
axios是一个基于Promise的HTTP请求客户端,用来发送请求,也是vue2.0官方推荐的,同时不再对vue-resource进行更新和维护

参考:GitHub上搜索axios,查看API文档

2. 使用axios发送AJAX请求

2.1 安装axios并引入

npm install axios -S
也可直接下载axios.min.js文件

2.2 基本用法

axios([options])  
axios.get(url[,options]);
    传参方式:
        1.通过url传参
        2.通过params选项传参
axios.post(url,data,[options]);
    axios默认发送数据时,数据格式是Request Payload,并非我们常用的Form Data格式,
    所以参数必须要以键值对形式传递,不能以json形式传参
    传参方式:
        1.自己拼接为键值对
        2.使用transformRequest,在请求发送前将请求数据进行转换
        3.如果使用模块化开发,可以使用qs模块进行转换

axios本身并不支持发送跨域的请求,没有提供相应的API,作者也暂没计划在axios添加支持发送跨域请求,所以只能使用第三方库

3. 使用vue-resource发送跨域请求

3.1 安装vue-resource并引入

cnpm install vue-resource -S

3.2 基本用法

使用this.$http发送请求  
    this.$http.get(url, [options])
    this.$http.head(url, [options])
    this.$http.delete(url, [options])
    this.$http.jsonp(url, [options])
    this.$http.post(url, [body], [options])
    this.$http.put(url, [body], [options])
    this.$http.patch(url, [body], [options]) 
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>发送AJAX请求</title>
	<script src="js/vue.js"></script>
	<script src="js/axios.min.js"></script>
	<script src="js/vue-resource.min.js"></script>
	<script>
		window.onload=function(){
			new Vue({
				el:'#itany',
				data:{
					user:{
						// name:'alice',
						// age:19
					},
					uid:''
				},
				methods:{
					send(){
						axios({
							method:'get',
							url:'user.jsonaaa'
						}).then(function(resp){
							console.log(resp.data);
						}).catch(resp => {
							// console.log(resp);
							console.log('请求失败:'+resp.status+','+resp.statusText);
						});
					},
					sendGet(){
						// axios.get('server.php?name=tom&age=23')
						axios.get('server.php',{
							params:{
								name:'alice',
								age:19
							}
						})
						.then(resp => {
							console.log(resp.data);
						}).catch(err => {
							console.log('请求失败:'+err.status+','+err.statusText);
						});
					},
					sendPost(){
						// axios.post('server.php',{
						// 		name:'alice',
						// 		age:19
						// })
						// axios.post('server.php','name=alice&age=20&') //方式1
						axios.post('server.php',this.user,{
							transformRequest:[
								function(data){
									let params='';
									for(let index in data){
										params+=index+'='+data[index]+'&';
									}
									return params;
								}
							]
						})
						.then(resp => {
							console.log(resp.data);
						}).catch(err => {
							console.log('请求失败:'+err.status+','+err.statusText);
						});
					},
					getUserById(uid){
						axios.get(`https://api.github.com/users/${uid}`)
						.then(resp => {
							// console.log(resp.data);
							this.user=resp.data;
						});
					},
					sendJSONP(){
						//https://sug.so.360.cn/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8&format=json&fields=word&word=a
						this.$http.jsonp('https://sug.so.360.cn/suggest',{
							params:{
								word:'a'
							}
						}).then(resp => {
							console.log(resp.data.s);
						});
					},
					sendJSONP2(){
						//https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=a&json=1&p=3&sid=1420_21118_17001_21931_23632_22072&req=2&csor=1&cb=jQuery110208075694879886905_1498805938134&_=1498805938138
						this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',{
							params:{
								wd:'a'
							},
							jsonp:'cb' //百度使用的jsonp参数名为cb,所以需要修改
						}).then(resp => {
							console.log(resp.data.s);
						});
					}
				}
			});
		}
	</script>
</head>
<body>
	<div id="itany">
		<button @click="send">发送AJAX请求</button>

		<button @click="sendGet">GET方式发送AJAX请求</button>

		<button @click="sendPost">POST方式发送AJAX请求</button>
		<hr>
		<br>

		GitHub ID: <input type="text" v-model="uid">
		<button @click="getUserById(uid)">获取指定GitHub账户信息并显示</button>
		<br>
		姓名:{{user.name}} <br>
		头像:<img :src="user.avatar_url" alt="">
		
		<hr>

		<button @click="sendJSONP">向360搜索发送JSONP请求</button>

		<button @click="sendJSONP2">向百度搜索发送JSONP请求</button>

	</div>
</body>
</html>
原文地址:https://www.cnblogs.com/wspblog/p/9844986.html