二次封装简化版
2022-02-27 本文已影响0人
好多柱
module.exports = {
lintOnSave:false,
devServer: {
open:true, //启动项目时自动打开浏览器
host: 'localhost',
port: '8082',
proxy: { //解决跨域问题
'/api': {
target: ' http://',
changeOrigin: true,
// pathRewrite:{
// '^/api':''
// }
}
}
},
// 全局的SASS引入
需要引入依赖 node - sass 、 sass - loader
这里安装 一定要指定版本,^4.14.1表示大于当前版本,默认 sass 的版本太高,webpack 编译时出现了错误,这时需要换成低版本 npm i node-sass@4.14.1 --save-dev
//版本过高的解决办法; https://blog.csdn.net/qq_38157825/article/details/114318772
css: {
loaderOptions: {
sass: {
prependData :`@import "./src/common/css/global.scss";`
}
}
}
}
gloabal.scss
$colorRed : red;
在页面中可以直接使用
.guess{
color:$colorRed;
}
axios二次封装:
service.js
import axios from 'axios'
import vue from '../main'
const service = axios.create({
baseURL: '/api',
timeout:5000
})
//获取token
function getTokenBylocal() {
let token = sessionStorage.getItem('token')
return token
}
// 请求拦截
service.interceptors.request.use(
config => {
if (getTokenBylocal()) {
config.headers['X-Auth-Token'] = getTokenBylocal()
} else {
vue.$router.push('/login')
}
return config
},
error => {
return Promise.reject(error)
}
)
// 响应拦截
service.interceptors.response.use(
response => {
let res = response.data
if (response.status == '400') {
vue.$router.push('/login')
}
return Promise.resolve(res)
},
error => {
return Promise.reject(error)
}
)
export default service
common.js
import service from './service'
export function requestOfPost(url, data) {
return service.post(url,data)
}
export function requestOfGet(url, data) {
return service.get(url,data)
}
api.js
import { requestOfGet } from './common'
export function getRequest(url, data) {
return new Promise((resolve, reject) => {
requestOfGet(url, data).then(res => {
resolve(res)
}
).catch(error => {
reject(error)
}
)
})
}
url.js
//统一管理所有URL
const url = {
login:'/v1/regions'
}
export default url
login.vue
<template>
<div>
Login...
<button @click="getData">登录</button>
</div>
</template>
<script>
import url from '../../request/url.js'
import {getRequest} from '../../request/api.js'
export default {
methods: {
async getData() {
try {
getRequest(url.login).then(()=>{
console.log('接口请求成功...')
sessionStorage.setItem('token','4366d5b51c36471688b54d3cb831f591')
this.$router.push('/')
})
} catch (error) {
console.log('error',error);
}
}
},
}
</script>
一个打包优化
//vue.config.js
const uglifyJsPlugin=require('uglifyjs-webpack-plugin);
let isProduction = process.env.NODE_ENV;
// 打包优化
configureWebpack : config => {
// 生产环境相关配置
if ( isProduction == "production"){
// 代码压缩
config.plugins.push (
new UglifyPsPlugin ({
uglifyOptions :{
//生产环境自动剧除 console
warnings : false ,
compress :{
//warnings : false ,//若打包错误,则注释这行
drop _ debugger : true ,
drop _ console : true ,
pure _ funcS :[ console.log]
}
}
})
}
}