前端技术

Vue.js Ajax(axios)

2021-04-30 66 1

简介 Vue.js Ajax(axios)

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

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

Github开源地址: https://github.com/axios/axios

安装方法
使用 cdn:

<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 install axios
使用 bower:

$ bower install 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(function (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(function (error) { // 请求失败处理
       console.log(error);
     });
 }
})
</script>

尝试一下 »
GET 方法传递参数格式如下:

传递参数说明
// 直接在 URL 上添加参数 ID=12345
axios.get(‘/user?ID=12345’)
 .then(function (response) {
   console.log(response);
 })
 .catch(function (error) {
   console.log(error);
 });

// 也可以通过 params 设置参数:
axios.get(‘/user’, {

点赞 1

文章评论

欢迎您:

阿文博客

人生的价值,并不是用时间,而是用深度量去衡量的。——列夫·托尔斯泰

59 文章 5993 浏览 5 评论

站点信息

  • 建站时间:2021-08-03
  • 更新时间:2021-08-03
  • 网站程序:终点线
  • 主题模板《今夕何夕》
  • 文章统计59篇文章
  • 标签总数14