文章目录
element-plus
element-plus-icons
axios
qs
mockjs
安装
cnpm install element-plus --save
cnpm install @element-plus/icons-vue --save
cnpm install axios vue-axios --save
cnpm install qs --save
cnpm install mockjs --save-dev
element-plus
element-plus-icons
axios
qs
mockjs
引用
main中引用
import {createApp} from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
//导入封装的axios
import axios from './axios'
import VueAxios from 'vue-axios'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElIconModules from '@element-plus/icons-vue'
// app.config.globalProperties.$axios=axios
//use(VueAxios, axios) 组件中使用 this调用axios
const app=createApp(App)
//全局引入icons
for (let iconName in ElIconModules) {
app.component(iconName, ElIconModules [iconName])
}
app.use(store).use(router).use(ElementPlus).use(VueAxios, axios).mount('#app')
require('./mock')
axios
前后置拦截处理
import axios from 'axios'
import router from './router'
import {ElMessage} from 'element-plus';
// axios.defaults.baseURL = "http://localhost:8081"
const request = axios.create({
timeout: 5000,
headers: {
'content-type': 'application/json;charset=utf-8'
}
})
request.interceptors.request.use(config => {
config.headers['token'] = localStorage.getItem("token")
return config
})
request.interceptors.response.use(response => {
let data = response.data;
if (200 === data.code) {
return response
} else {
let msg = data.msg ? data.msg : '系统异常';
ElMessage.error(msg)
return Promise.reject(msg)
}
}, error => {
//优先展示返回的信息
if (error.response.data) {
error.message = error.response.data.msg
}
if (401 === error.response.status) {
router.push('/login')
}
ElMessage.error(error.message, {duration: 3000})
return Promise.reject(error)
})
export default request