Vue发送请求之Axios---kalrry

一、简介

vue-resource是vue自带的发送请求方式
Axios是第三方插件来完成

  1. vue本身不支持发送Axios请求,需要使用vue-resource(vue1.0版本)、axios(vue2.0版本)等插件实现
  2. axios是一个基于Promise的HTTP请求客户端,用来发送请求,也是vue2.0官方推荐的,同时不再对vue-resource进行更新和维护
  3. 参考:GitHub上搜索axios,查看API文档

二、Axios

引入对应的js文件,可以使用在线的

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

1. GET请求

实例1:简单的读取 JSON 数据,使用 response.data 读取 JSON 数据
json

<div id="app">
	<button @click="showMessage()">查看test.txt文本内容</button>
</div>

<script type="text/javascript">
	window.onload = function() {
    
    
		new Vue({
    
    
			el: '#app',
			methods: {
    
    
				showMessage: function() {
    
    
					axios.get('test.json').then(function(response) {
    
    
						console.log(response.data,typeof response.data)
					}, function() {
    
    
						alert("请求失败")
					}).catch(function(error) {
    
    
						console.log(error);
					})
				}
			}
		})
	}
</script>

get方法传递参数

1、直接在 URL 上添加参数
2、通过 params 设置参数

// 直接在 URL 上添加参数 ID=12345
axios.get('/user?ID=12345')
  .then(function (response) {
    
    
    console.log(response);
  })
  .catch(function (error) {
    
    
    console.log(error);
  });
 
// 也可以通过 params 设置参数:
axios.get('/user', {
    
    
    params: {
    
    
      ID: 12345
    }
  })
  .then(function (response) {
    
    
    console.log(response);
  })
  .catch(function (error) {
    
    
    console.log(error);
  });

3、POST传递参数

axios.post('/user', {
    
    
    firstName: 'Fred',        // 参数 firstName
    lastName: 'Flintstone'    // 参数 lastName
  })
  .then(function (response) {
    
    
    console.log(response);
  })
  .catch(function (error) {
    
    
    console.log(error);
  });

三、在脚手架中使用

axios发送AJAX请求

1、安装axios并引入

  1. npm install axios -S #直接下载axios组件,下载完毕后axios.js就存放在node_modules\axios\dist中
  2. 网上直接下载axios.min.js文件
  3. 通过script src的方式进行文件的引入
  4. 发送get请求
    基本使用格式:
    格式1:axios([options]) #这种格式直接将所有数据写在options里,options其实是个字典
    格式2:axios.get(url[,options]);

2、传参方式:

  1. 通过url传参
  2. 通过params选项传参

3、发送AJAX请求

el:'#itany',

data:{
    
    undefined

user:{
    
    undefined

name:'alice',

age:19},

},

methods:{
    
    undefined

send(){
    
    undefined

axios({
    
    undefined

method:'get',

url:'http://www.baidu.com?name=tom&age=23'}).then(function(resp){
    
    undefined

console.log(resp.data);

}).catch(resp=>{
    
    undefined

console.log('请求失败:'+resp.status+','+resp.statusText);

});

},

sendGet(){
    
    undefined

axios.get('server.php',{
    
    undefined

params:{
    
    undefined

name:'alice',

age:19}

})

.then(resp=>{
    
    undefined

console.log(resp.data);

}).catch(err=>{
    
    //console.log('请求失败:'+err.status+','+err.statusText);

});

},

}

});

}

猜你喜欢

转载自blog.csdn.net/weixin_45406712/article/details/124223060