zoukankan      html  css  js  c++  java
  • Vue封装简单的axios库

    1.新建http.js文件,封装axios get post 方法:

     1 import axios from 'axios'
     2 import qs from 'qs'
     3 import 'es6-promise'
     4 
     5 axios.defaults.baseURL = '/api';
     6 
     7 export function get(url, params) {
     8   return new Promise((resolve, reject) => {
     9     axios.get(url, {
    10       params: params
    11     }).then(res => {
    12       resolve(res.data)
    13     }).catch(err => {
    14       reject(err)
    15     })
    16   })
    17 }
    18 
    19 export function post(url, data) {
    20   return new Promise((resolve, reject) => {
    21     axios.post(url, qs.stringify(data), {
    22         headers: {
    23           'Content-Type': 'application/x-www-form-urlencoded',
    24         }
    25       }
    26     ).then(res => {
    27       resolve(res.data)
    28     }).catch(err => {
    29       reject(err)
    30     })
    31   })
    32 }

    2.新建api.js文件,封装调用的接口

    1 import {get, post} from './http'
    2 
    3 export function getNewPublish() {
    4   const result = get('/ad/newestPublishAdMaterialInfo1');
    5   return result;
    6 }

    3.在组件中使用

    1 import {getNewPublish} from '../../api/api'
    2 
    3 let result = getNewPublish();
    4 
    5 result.then(res => {
    6    console.log(res);
    7 }).catch(err => {
    8    console.log(err);
    9 })
  • 相关阅读:
    jQuery Asynchronous
    Best Pratices——Make the Web Faster
    Asynchronous
    Deferred
    w3 protocol
    Android 设置wifi共享电脑服务器资源
    VC++ 6.0创建MFC工程时的初级备要点(二)
    【LeetCode】Pascal's Triangle II (杨辉三角)
    POJ 1564 Sum It Up(DFS)
    CSS写表格
  • 原文地址:https://www.cnblogs.com/tian-long/p/8418771.html
Copyright © 2011-2022 走看看