vue学习6 axios和vue-axios

1、基本用法

安装:

1 cnpm i axios --save
2 在 main.js 中引入 axios:
import axios from 'axios'
Vue.prototype.$axios = axios

在组件中使用:

<script>
	export default {
		mounted(){
			this.$axios.get('/goods.json').then(res=>{
				console.log(res.data);
			})
		}
	}
</script>

2、axios请求方法:

axios可以请求的方法:

get:获取数据,请求指定的信息,返回实体对象
post:向指定资源提交数据(例如表单提交或文件上传)
put:更新数据,从客户端向服务器传送的数据取代指定的文档的内容
patch:更新数据,是对put方法的补充,用来对已知资源进行局部更新
delete:请求服务器删除指定的数据

比如get:

input type="button" value="get请求" class="get">
<input type="button" value="post请求" class="post">

<script>
   document.querySelector(".get").onclick = function () {

    axios.get("https://xiaohua.zol.com.cn/")
    .then(function(response){
        console.log(response);
    },function(err){
        console.log(err);
    })
 }  
    

axios请求配置:

this.$axios.get('/goods.json',{
				timeout: 3000
			}).then()


3 错误处理:

比如:

this.$axios.get('/url').then(res={

			}).catch(err=>{
				//请求拦截器和响应拦截器抛出错误时,返回的err对象会传给当前函数的err对象
				console.log(err);
			})


取消正在进行的http请求:

let source = this.$axios.CancelToken.source();

this.$axios.get('/goods.json',{
				cancelToken: source
			}).then(res=>{
				console.log(res)
			}).catch(err=>{
				console.log(err)
			})
source.cancel('取消后的信息');

 

axios是一个基于Promise的HTTP客户端库,可以用于浏览器和Node.js环境中向服务器发送HTTP请求。它是一个功能强大且易于使用的库,可以与Vue.js等前端框架很好地配合使用。 vue-axios是一个适用于Vue.js的插件,它将axios集成到Vue.js中,使我们可以在Vue组件中更方便地使用axios发送HTTP请求。通过使用vue-axios插件,我们可以在Vue实例和Vue组件中直接使用this.$http来代替axios实例来发送请求,简化了我们的代码并提高了开发效率。 虽然我们也可以直接使用axios来发送请求,但使用vue-axios插件更符合Vue整体生态环境的设计原则。直接写原型链的方式可能会显得比较粗暴,并且不太推荐,除非是在底层实现的时候。因此,我们更推荐使用vue-axios插件的方式来结合Vue.js框架使用axios。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [axiosvue-axios](https://blog.csdn.net/qq_43654065/article/details/121288529)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Vue axiosvue-axios的关系及使用区别](https://blog.csdn.net/u014641168/article/details/126096526)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值