分析:

(1)axios处理接口请求。可能需处理请求拦截,响应拦截,不同类型的请求,所以需要一个http.js文件

(2)请求都是基于相关环境的,所以需要一个url.js处理环境

(3)可根据不同模块将同一个模块的请求放在一起,所以可将test模块的请求放在test.js中

(4)新建一个文件,将不同模块的请求都集合在一起,所以需要一个api.js

(5)使用

目录:

main.js  将所有api挂载在vue原型上

import api from './api/api.js'

Vue.prototype.$api = api;

url.js

/*
* @Author: lingxie
* @Date: 2020-06-29 11:37:09
* @Descripttion:
*/
let baseUrl;
if(process.env.NODE_ENV == 'development'){
baseUrl = '/api' //此处使用了代理,请看vue.config.js
}else if(process.en .NODE_ENV == 'test'){
baseUrl = 'https://www.test.com'
}else if(process.en .NODE_ENV == 'production'){
baseUrl = 'https://www.prod.com'
}
export default baseUrl

http.js

/*
* @Author: lingxie
* @Date: 2020-06-29 09:36:50
* @Descripttion:
*/
import axios from 'axios';
import qs from 'qs';
import baseurl from './url';
console.log(baseurl);
// 创建axios实例
// const instance = axios.create({
// baseURL:this.$utils.baseURL,
// timeout:2000
// });
const instance = axios.create();

instance.defaults.baseURL = baseurl;
instance.defaults.timeout = 2000;
// 添加请求拦截器
instance.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
// config.headers['token'] = '1111111111111111'
if(config.method === 'post'){
// config.data = qs.stringify(config.data);
// config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
// config.headers['token'] = '222222222222'
}
return config; }, function (err) {
// 对请求错误做些什么
return Promise.reject(err);
}); // 添加响应拦截器
instance.interceptors.response.use(function (res) {
// 对响应数据做点什么
return res;
}, function (err) {
// 对响应错误做点什么
return Promise.reject(err);
}); function get(url,params){
return new Promise((resolve,reject)=>{
instance.get(url,{
params:params
}).then(res =>{
resolve(res.data);
}).catch(err=>{
reject(err)
});
});
}; // 适合于Content-Type'为'application/x-www-form-urlencoded post请求
// 客户端把form数据转换成一个字串append到url后面,用?分割。
function post(url,params,){
console.log(qs.stringify(params));// 形如type=top&key=136f240edd201502102577573e95f208
const header ={
headers:{
'Content-Type':'application/x-www-form-urlencoded',
'token':'333333333333333333'
}
}
return new Promise((resolve,reject)=>{
instance.post(url,qs.stringify(params),header).then(res =>{
resolve(res.data);
}).catch(err=>{
reject(err)
});
});
}; // 适合于Content-Type'为'multipart/form-data post请求
function post1(url,params,){
console.log(qs.stringify(params));// 形如type=top&key=136f240edd201502102577573e95f208
const header ={
headers:{
'Content-Type':'multipart/form-data; charset=utf-8;',
'token':'4444444'
}
}
return new Promise((resolve,reject)=>{
instance.post1(url,qs.stringify(params),header).then(res =>{
resolve(res.data);
}).catch(err=>{
reject(err)
});
});
}; export {
get,
post,
post1
};

test.js

/*
* @Author: lingxie
* @Date: 2020-06-29 10:43:02
* @Descripttion:
*/
import {get,post,post1} from './http'; const toutiao =params => post('/toutiao/index',params);//新闻头条
const joke =params =>get('/joke/content/list.php',params);//笑话 const test ={
toutiao,
joke
}
export default test

api.js

import test from './test' //引入test模块的api

const api = {
test
}
export default api;

vue.config.js代理配置

/*
* @Author: lingxie
* @Date: 2020-04-23 13:38:18
* @Descripttion:
*/
module.exports = { devServer: {
proxy: {
// 匹配所有以api开头的请求路径
'/api': {
target: 'http://v.juhe.cn/',
changeOrigin: true, // 把api替换掉
pathRewrite: {
'^/api': ''
}
}
}
}, }

使用:

<!--
* @Author: lingxie
* @Date: 2020-04-23 13:35:57
* @Descripttion:
-->
<template>
<div class="about"> </div>
</template>
<script>
export default { created(){
this.fetch_toutiao();
this.fetch_joke();
},
methods:{
fetch_toutiao(){
let jsonData ={
type:'top',
key:'136f240edd201502102577573e95f208'
}
this.$api.test.toutiao(jsonData).then(res=>{
console.log(res);
});
}, fetch_joke(){
console.log('1111', this.$api);
let jsonData ={
sort:'asc',
time:'1418816972',
key:'14ec2ba9cfdfa38a712ae8c5e80a728c'
}
this.$api.test.joke(jsonData).then(res=>{
console.log(res);
});
} }
}
</script>

vue - axios简单封装的更多相关文章

  1. vue axios 简单封装以及思考

    先安装 axios npm install axios axios的详细介绍以及用法 就不多说了请 移步 github ➡️  https://github.com/axios/axios 下面是简单 ...

  2. vue axios接口封装、Promise封装、简单的axios方法封装、vue接口方法封装、vue post、get、patch、put方法封装

    相信大家在做前后端数据交互的时候都会给请求做一些简单的封装就像之前封装ajax方法一样axios的封装也是一样的简单下面这个就是封装的axios的方法,require.js import axios ...

  3. axios简单封装

    写在最前面 新手前端刚刚接触vue,感觉真的好用.项目中需要使用axios,然后学习了一下.借鉴网上一些大佬的经验,现在分享一下axios的简单封装,如果有什么错误的地方,请大家指出. axios安装 ...

  4. Vue.js(18)之 axios简单封装

    基于vue-cli2.x封装axios src目录 axios.js import axios from 'axios' import { Indicator, Toast } from 'mint- ...

  5. Vue: axios 请求封装及设置默认域名前缀 (for Vue 2.0)

    1. 实现效果 以get方法向http://192.168.32.12:8080/users 发起请求.获取数据并进行处理 this.apiGet('/users', {}) .then((res) ...

  6. VUE axios请求 封装 get post Http

    创建httpService.js 文件 import axios from 'axios'; import { Loading , Message } from 'element-ui'; impor ...

  7. Vue Axios 的封装使用

    目录 Axios 说明 安装 Axios 请求配置 响应结构 常用请求方法 默认值配置 全局的 请求配置项 自定义实例默认值 配置的优先顺序 拦截器 个人完整 axios 配置 Axios 说明 Ax ...

  8. vue axios简单配置

    参考:https://www.cnblogs.com/sophie_wang/p/7844119.html 1. 安装 npm install axios 2. main.js import axio ...

  9. 用XHR简单封装一个axios

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  10. vue中axios的封装以及简单使用

    一.axios的封装 在vue中为了使用axios使用方便,不需要每一个模块进行导入,就需要对其进行封装: 1.新建http.js模块 import axios from 'axios' // 设置基 ...

随机推荐

  1. dfs-入门模板

    模板 void dfs()//参数用来表示状态 { if(到达终点状态) { ...//根据题意添加 return; } if(越界或者是不合法状态) return; if(特殊状态)//剪枝 ret ...

  2. 富文本编辑器第一次正常显示,第二次渲染失败 -----在使用laravel-admin 时

    第二次显示 解决方法: 在每次获取富文本编辑器实例的时候,先删除一下,避免之前已经实例化造成的渲染失败

  3. 《CSOL大灾变》Mobile移植记录——购买区域

    在CSOL大灾变模式中,购买武器只能出现在特定区域,如下:    这里可以通过添加一些不渲染的BOX(如图中的蓝色BOX)作为触发器,然后检测玩家与之触发后才能弹出购买菜单. 在JmonkeyEngi ...

  4. 基于北斗gps设计的NTP网络时间服务器

    基于北斗gps设计的NTP网络时间服务器 基于北斗gps设计的NTP网络时间服务器 京准电子科技官微--ahjzsz 随着5G等新型基础设施持续建设和发展,在未来万物互联的庞大信息网络中,跨路由节点之 ...

  5. LENGTH,LENGTHB

    LENGTH 1.语法 length(string) 2.说明: 统计字段的字符长度 3.示例: select length('abcd') from dual; --返回值:4 select len ...

  6. 808.11ac的MAC层

    MAC层是802.11的主要功能部分.上层应用通过调用MAC层提供的接口原语调用MAC层的功能. 在内部,MAC由除了函数还有数据,叫MIB,存储MAC的各种参数.SME是一个单独的模块,用来跟接口函 ...

  7. HIVE 调优思路和实践

    1,数据存储调优 1.1 设置压缩: 设置中间数据/输出结果压缩传输,使用snappy格式. hive-site.xml: set hive.exec.compress.output = true # ...

  8. vue学习之-----组件递归调用

    1.关键点 2.父组件 <template> <div> <div class="btn-title"> <el-button @clic ...

  9. 路飞项目 day02 全局日志、全局异常处理、封装Response、数据库准备

    一.路飞项目全局日志配置 ​ 那个代码不用死记硬背,知道一些地方是啥意思即可 1.复制django自带的日志模块的大代码到dev(settings)文件中 LOGGING = { 'version': ...

  10. linux与windows互通

    https://www.cnblogs.com/zhouby/p/10724149.html