【4】axios 获取数据

API:https://www.kancloud.cn/yunye/axios/234845

基于axios进行二次封装

安装axios

npm install axios --save

安装成功

 

【src】- 新建文件夹【api】存放与请求相关的数据 -  新建js辅助文件【helpers.js】

  封装

  

//引入axios
import axios from 'axios'

const ERR_OK = 0
//暴露一个get方法 对于同一个url可以返回一个方法
export function get(url){
    return function (params){
        return axios.get(url, {
            params
        }).then((res) => {
            const {errno, data} = res.data;//这个data是指包含errno和data的对象,而不是json数据里的data变量
            if(errno == ERR_Ok){
                return data
            }
        }).catch(()=>{
            
        })
    }
}

 

 【src】- 新建文件夹【api】 -  新建js辅助文件【index.js】 使用封装函数 传入具体地址

//导入get方法
import {get} from './helpers'

//传入url参数值获取数据对象传给getSeller(是一个函数)
const getSeller = get('api.seller')

//暴露getSeller 供使用
export{
    getSeller
}

 

在【app.vue】中使用

先引入index.js的函数

import { getSeller } from 'api'
export default {
        name: 'app',
        data(){
            return{
                seller:{}
            }
        },
        components: {
            VHeader
        },
        created() {
            getSeller().then((seller) => {
                this.seller = seller
            })
        },
    }

查看请求情况

 

 代码优化:

 

posted @ 2018-12-04 00:32  Du.Du  阅读(388)  评论(0编辑  收藏  举报