axios的简单使用

axios是一个通用的ajax请求库,vue 2.0以后,推荐使用axios

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

使用:

1、下载安装

npm install axios

2、引入(在哪里使用就在哪里引入)

import axios from 'axios'

3、使用(引入后就可以直接使用)

常用的两个方法:axios.get()/axios.post(),两者返回的均为promise对象

语法:axios.get(url,params)   axios.post(url,params)

params 是传递的参数,用对象形式

举例:

<template>
    <div>
        <div v-if="!repoUrl">loading</div>
        <div v-else>most star repo is <a :href='repoUrl'>{{repoName}}</a></div>
    </div>
</template>

<script>
   import axios from 'axios';
   export default{
       data(){
           return {
               repoUrl:'',
               repoName:''
           }
       },
       mounted(){//初始化完成后触发,发送ajax请求获取数据
        //使用axios发送ajax请求
        axios.get('https://api.github.com/search/repositories?q=v&sort=stars').then(respose=>{
            const result = respose.data;
            const mostRepo = result.items[0];
            this.repoUrl = mostRepo.html_url;
            this.repoName = mostRepo.name;
        }).catch(error=>{
            alert('error!');
        })

       }

   }
</script>

更多用法及API,见官网

 

posted @ 2018-11-20 10:44  心晴安夏  阅读(721)  评论(0编辑  收藏  举报