Vue之axios的简单实用

73 篇文章 1 订阅
4 篇文章 1 订阅

在以前的项目中使用了Promise对数据进行请求,但是在使用过程中有的数据会请求不到,这次采用封装过的axios进行数据交互

axios能做什么?

  • 支持XMLHTTPRequest
  • 支持promise
  • 支持CSRF

 

一,在vue中安装axios

npm install axios --save

 当然对于传统页面可以通过<script></script>标签引用axios的文件

二、配置axios到全局环境

在vue项目中找到main.js文件,这个就是vue项目的js入口文件,在里面添加对axios的引用:

import axios from 'axios'

Vue.prototype.$axios = axios

然后在对应的页面使用

            this.$axios.post('/url',{
                param1:this.message,
                param2:this.note

            })
            .then(function(response){
                alert("您的请求已提交!谢谢");
            })
            .catch(function(error){
                alert("由于网络故障,请求提交失败!请您稍后再试");
            })


            this.$axios.get('https:www.baidu.com')
            .then(function(response){
                console.log("response:"+response);
            })
            .catch(function(error){
                console.log("error:"+error);
            })

 

配置方法二

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
 
Vue.use(VueAxios, axios)


//使用方法

Vue.axios.get(api).then((response) => {
  console.log(response.data)
})
 
this.axios.get(api).then((response) => {
  console.log(response.data)
})
 
this.$http.get(api).then((response) => {
  console.log(response.data)
})


然后再打开网页就可以实现请求。

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值