Axios请求数据的使用方法浅析

请求数据的第三方插件Axios,可以支持vue,node ,react

axios:基于Promise的HTTP客户端,用于浏览器和node.js

使用步骤

1:安装axios

npm i axios --save / cnpm

2:

哪里用就在那里引入

import Axios from 'axios' / const axios = require('axios');



3:直接在组件中应用

axios.get('/user')

.then(function (response) {

// handle success

console.log(response);

})

.catch(function (error) {

// handle error

console.log(error);

})

.then(function () {

// always executed

});

代码示例:

请求数据前

<template>
    <div id="life">
        <h3>生命首期函数</h3>
             <ul>
                 <li v-for="(item,index) in list" :key="index">
                     {{item.catname}}
                 </li>
             </ul>      
        <br>
        <button @click="getData()">请求数据</button>
    </div>
</template>

<script>

import Axios from 'axios'
export default {
    data(){
        return{
            list:[]
        }
    },
    methods: {
        getData(){
            var api='http://www.phonegap100.com/appapi.php?a=getPortalCate'
            Axios.get(api)
            .then((response)=> {
                //尽量用箭头函数,避免this的指向问题
                this.list=response.data.result
            })
            .catch((error)=> {
                // handle error
                console.log(error);
            })
           
        }
    },
    mounted(){
         /* 渲染dom完成时请求数据,操作Dom时常用 */
        console.log('实力挂载完成');
        this.getData();
        
    }
}

请求数据后:

关于axios请求数据的具体步骤就分析到这,欢迎各路大神指教更好的套路!!!

猜你喜欢

转载自blog.csdn.net/W2457307263/article/details/88035263
今日推荐