vue 中使用axios

本文详细介绍了在 Vue.js 应用中如何使用 Axios 进行 AJAX 请求,包括 GET 和 POST 方法,处理并发请求,配置选项,以及如何创建实例和使用拦截器。此外,还讨论了在不同环境下的数据序列化和取消请求的方法。
摘要由CSDN通过智能技术生成

1.Vue.js Ajax(axios)

Vue.js 2.0 版本推荐使用 axios 来完成 ajax 请求。

Axios 是一个基于 Promise 的 HTTP 库,可以用在浏览器和 node.js 中。

安装方法:

使用adn(arc引入):

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

<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>

使用npm:

npm i axios

使用 bower:

bower i axios

使用 yarn:

yarn add axios

浏览器支持情况:

 get方法:

我们可以简单读取JSON数据:

get实例:



new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios
      .get('https://www.runoob.com/try/ajax/json_demo.json')
      .then(response => (this.info = response))
      .catch( (error) => { // 请求失败处理
        console.log(error);
      });
  }
})

使用 response.data 读取 JSON 数据:

get实例:


<div id="app">
  <h1>网站列表</h1>
  <div
    v-for="site in info"
  >
    {
  { site.name }}
  </div>
</div>
<script type = "text/javascript">
new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios
      .get('https://www.runoob.com/try/ajax/json_demo.json')
      .then(response => (this.info = response.data.sites))
      .catch( (error) => { // 请求失败处理
        console.log(error);
      });
  }
})
</script>

GET 方法传递参数格式如下:

传递参数说明


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

POST方法:

POST 实例


new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios
      .post('https://www.runoob.com/try/ajax/demo_axios_post.php')
      .then(response => (this.info = response))
      .catch((error) => { // 请求失败处理
        console.log(error);
      });
  }
})

POST 方法传递参数格式如下:

传递参数说明


axios.post('/user', {
    firstName: 'Fred',        // 参数 firstName
    lastName: 'Flintstone'    // 参数 lastName
  })
  .then((response) => {
    console.l
  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值