请求接口封
一般来说请求接口封装是很常见的,就好比你要经常拿一个东西,
当然你需要把这个东西好好的规划在一个地方,方便以后用来查找
vue封装axos请求
请求接口带代理的封装
这里是以cnode接口为例子
request.js 这个文件是封装请求axios 据
index.js 这个文件是封装单独独立的接口数
request.js
import axios from 'axios'
import { MessageBox, Loading, Message } from 'element-ui'
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_URL,
timeout: 5000
})
let loadingAll;//配置一个loading实例,方便后面使用
let loading_count = 0; //请求计数器
function startLoading() {
if (loading_count == 0) {
// 调用其他loading效果在页面引入放在这个块级里面
loadingAll = Loading.service({
lock: true,
text: "别急,请求加载数据中...",
fullscreen: true,
background: "rgba(0,0,0,0.7)",
spinner: 'el-icon-loading',//自定义加载图标类名
});
}
//请求计数器
loading_count++;
}
function endLoading() {
loading_count--;//只要进入这个函数,计数器就自减,直到。。
if (loading_count <= 0) {
loadingAll.close();
}
}
// 请求拦截器(放token)
service.interceptors.request.use(
config => {
startLoading()//开启loading
/*
判断是否需要token,则放在请求头。
*/
// var token = sessionStorage.getItem('setMuToken')
// if(token){
// config.headers['token']= token;
// return config;
// }else{
// console.log('token为空')
// }
return config;
},
error => {
return Promise.reject(error)
}
)
// 响应拦截器(放提示信息)
service.interceptors.response.use(
response => {
endLoading()//关闭loading
/*
进行判断是否为200 有则提示正确信息,无提示err信息
判断是否200根据返回情况而定
*/
if (response.data === '200') {
Message({
message: response.data.meta.msg,
type: 'success',
duration: 5 * 1000
})
} else {
Message({
message: response.data.meta.msg,
type: 'error',
duration: 5 * 1000
})
}
return response.data
},
error => {
endLoading()//关闭loading
//判断错误信息进行提示
if (error && error.response) {
// 1.公共错误处理
// 2.根据响应码具体处理
switch (error.response.status) {
case 400:
error.message = '错误请求'
break;
case 401:
error.message = '未授权,请重新登录'
break;
case 403:
error.message = '拒绝访问'
break;
case 404:
error.message = '请求错误,未找到该资源'
window.location.href = "/NotFound"
break;
case 405:
error.message = '请求方法未允许'
break;
case 408:
error.message = '请求超时'
break;
case 500:
error.message = '服务器端出错'
break;
case 501:
error.message = '网络未实现'
break;
case 502:
error.message = '网络错误'
break;
case 503:
error.message = '服务不可用'
break;
case 504:
error.message = '网络超时'
break;
case 505:
error.message = 'http版本不支持该请求'
break;
default:
error.message = `连接错误${error.response.status}`
}
} else {
// 超时处理
if (JSON.stringify(error).includes('timeout')) {
Message.error('服务器响应超时,请刷新当前页')
}
}
Message.error(error.message)
return Promise.reject(error)
}
)
export default service
index.js
import service from "../util/request";
// get请求参数是存放在params
export function GetCode(params){
return service.request({
method: 'get',
url: '/topics',
params
})
}
// post的请求参数存放在data
export function PostCode(data){
return service.request({
method: 'post',
url: '/getCode/',
data
})
}
/*
/put是post的演变而来
都是通过body传递的,里面写data
一般put delect请求时
*/
export function edmit(id,params) {
return request({
url: `users/${id}`,
method: 'put',
id,
data:params//这样来写
})
}
在页面使用获取
<template>
<div class="home">
<div></div>
</div>
</template>
<script>
import { GetCode } from "../api/index";
export default {
name: "Home",
components: {},
created() {
this.listone();
},
methods: {
listone() {
let params = {
limit: 10,
};
GetCode({ params: { params } }).then((res) => {
console.log(res)
});
},
},
};
</script>
手动配置vue.config.js
https://cli.vuejs.org/zh/config/
找到vue官网
vue.config.js 是vue项目全局配置文件 该文件项目运行时可以自动识别 无需引入
我们这边放入代理 官网介绍
module.exports = {
devServer: {
proxy: {
"/capi": {
target: "https://jsbceshi.hfi-health.com:18188/mdggateway",
changeOrigin: true,
ws: true,
pathRewrite: {
"^/capi": ''
}
}
}
},
}
如果要请求代理第三方接口
同上所述
然后在把index.js里面的baseurl关闭 把http.js里面的请求改为斗鱼的后缀接口撒
assets文件夹
里面创建css js 引入reset.css rem.js
然后在全局man.js里面引入 在其他页面就可以直接使用撒
上传图片(无服务器)
这边到时候样式直接按照需要的去更改
效果图
代码
<template>
<div>
<!-- 新建时可以进行图片的新增和删除。修改时只能展示之前上传的图片,点重新上传会将之前上传的图片清空,之后可以进行重新上传图片的新增和删除 -->
<div class="img-group" v-if="isInsert">
<span class="control-label">上传图片</span>
<span class="help-block">(建议图片格式为:JPEG/BMP/PNG/GIF,大小不超过5M,最多可上传5张)</span>
<div class="control-form">
<ul class="upload-imgs">
<li v-if="imgLen>=5 ? false : true">
<input
type="file"
class="upload"
@change="addImg"
ref="inputer"
multiple
accept="image/png, image/jpeg, image/gif, image/jpg"
/>
<a class="add">
<i class="iconfont icon-plus"></i>
<p>点击上传</p>
</a>
</li>
<li v-for="(value, key) in imgs" :key="key">
<div class="imgBox">
<p class="img">
<viewer :images="images">
<img :src="getObjectURL(value)" />
</viewer>
<a class="close" @click="delImg(key)">×</a>
</p>
<div class="picName">{{value.name}}</div>
</div>
</li>
</ul>
</div>
</div>
<div class="img-group" v-else style="margin-left: 35px;">
<span class="control-label">重新上传图片</span>
<span class="help-block">(重新上传会覆盖之前图片!建议图片格式为:JPEG/BMP/PNG/GIF,大小不超过5M,最多可上传5张)</span>
<div class="control-form">
<ul class="upload-imgs" style="margin: 10px 0 30px 51px;">
<li v-if="imgLen>=5 ? false : true">
<input
type="file"
class="upload"
@change="addImg"
ref="inputer"
multiple
accept="image/png, image/jpeg, image/gif, image/jpg"
/>
<a class="add">
<i class="iconfont icon-plus"></i>
<p>点击重新上传</p>
</a>
</li>
<template v-if="!isReUpload">
<li v-for="(value, key) in reImgs" :key="key">
<div class="imgBox">
<p class="img">
<viewer :images="images">
<img :src="value" />
</viewer>
</p>
</div>
</li>
</template>
<template v-else>
<li v-for="(value, key) in imgs" :key="key">
<div class="imgBox">
<p class="img">
<viewer :images="images">
<img :src="getObjectURL(value)" />
</viewer>
<a class="close" @click="delImg(key)">×</a>
</p>
<div class="picName">{{value.name}}</div>
</div>
</li>
</template>
</ul>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return{
formData: new FormData(),
imgs: {}, // 循环生成的li的数据来源
imgLen: 0, // 上传图片的数量
isInsert: true, // 判断是否为新增
reImgs: [], // 详情传来的img的url
isReUpload: false, // 重新上传
images: [], // 详情预览大图数组
}
},
methods:{
addImg(event) {
this.isReUpload = true
this.reImgs = []
let inputDOM = this.$refs.inputer;
// 通过DOM取文件数据
this.fil = inputDOM.files;
let oldLen = this.imgLen;
let len = this.fil.length + oldLen;
if (len > 1) {
return false;
}
for (let i = 0; i < this.fil.length; i++) {
let size = Math.floor(this.fil[i].size / 1024);
if (size > 5 * 1024 * 1024) {
alert("请选择5M以内的图片!");
return false;
}
if (this.fil[i].name in this.imgs) {
alert("该文件已上传,请重新选择!")
} else {
this.imgLen++;
this.$set(this.imgs, this.fil[i].name, this.fil[i]);
}
//解决 input type=”file“ 相同文件change事件只执行一次的问题
this.$refs.inputer.value = null;
}
},
getObjectURL(file) {
var url = null;
if (window.createObjectURL != undefined) {
// basic
url = window.createObjectURL(file);
} else if (window.URL != undefined) {
// mozilla(firefox)
url = window.URL.createObjectURL(file);
} else if (window.webkitURL != undefined) {
// webkit or chrome
url = window.webkitURL.createObjectURL(file);
}
return url;
},
delImg(key) {
this.$delete(this.imgs, key);
this.imgLen--;
},
},
}
</script>
<style scoped>
.img-group {
margin-left: 63px;
margin-top: 30px;
font-size: 14px;
color: #606266;
font-weight: 700;
.control-label {
margin-right: 12px;
}
.control-form {
margin-top: 30px;
}
}
.upload-imgs {
margin: 10px 0 30px 22px;
overflow: hidden;
font-size: 0;
}
.upload-imgs li {
position: relative;
width: 168px;
height: 188px;
font-size: 14px;
display: inline-block;
padding: 10px;
margin-right: 25px;
border: 2px dashed #ccc;
text-align: center;
vertical-align: middle;
input {
opacity: 0;
}
}
.upload-imgs .add {
display: block;
background-color: #ccc;
color: #ffffff;
height: 144px;
padding: 10px 0;
p {
font-size: 20px;
line-height: 83px;
}
}
.upload-imgs .add .iconfont {
padding: 10px 0;
font-size: 40px;
}
.upload-imgs li .upload {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 168px;
height: 168px;
}
.upload-imgs .img {
position: relative;
width: 144px;
height: 144px;
line-height: 144px;
margin: 0;
}
.upload-imgs .img img {
width: 144px;
height: 144px;
vertical-align: middle;
}
.upload-imgs li .img .close {
display: block;
position: absolute;
right: -6px;
top: -14px;
line-height: 1;
font-size: 26px;
color: rgb(211, 23, 23);
font-weight: 400;
}
.imgBox {
position: relative;
}
.picName {
position: absolute;
left: 8px;
bottom: -27px;
line-height: 1.5;
font-size: 14px;
max-width: 130px;
color: #606266;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>
上传图片(有服务器)
加粗样式