【4】axios 獲取資料
阿新 • • 發佈:2018-12-04
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 }) }, }
檢視請求情況
程式碼優化: