vue3整合axios
3.1导入依赖
npm install axios
3.2新建util文件夹,创建api.js
import axios from 'axios'
import {ElLoading,ElMessage} from 'element-plus'
//创建axios实例
const instance = axios.create({
baseURL:'http://localhost:8888/',
timeout:5000
})
//创建ElLoading实例
let loadingInstance
//axios请求拦截器
instance.interceptors.request.use(config => {
loadingInstance = ElLoading.service({
//在data中配置loadingText,替换掉原来的text,达到每个页面请求的时候显示不同的loading文字
text:config.data['loadingText']||'请求中...'
})
return config
},error => {
loadingInstance.close()
return Promise.reject(error)
})
//aixos响应拦截器
instance.interceptors.response.use(response => {
loadingInstance.close()
let {data} = response
if (data.message){
if (data.code === 200){
ElMessage.success(data.message)
}else{
ElMessage.error(data.message)
}
}
return response
},error => {
loadingInstance.close()
ElMessage.error('请求出错,请重试')
})
export default instance;
3.3模块化引入,创建request.js
import api from './api'
export const login = (params) =>{
return api.post('/login',{loadingText:'登录中,请稍后...',...params})
}
4、Login.vue调用login方法
<template>
<div class="login-container">
<el-card class="login-card">
<h3 class="login-title">用户登录</h3>
<el-form ref="loginForm" :model="user" :rules="rules" label-width="80px" class="login-form">
<el-form-item prop="username" label="用户名">
<el-input v-model="user.username" placeholder="请输入用户名"></el-input>
</el-form-item>
<el-form-item prop="password" label="密码">
<el-input v-model="user.password" type="password" placeholder="请输入密码"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="userLogin">登录</el-button>
</el-form-item>
</el-form>
</el-card>
</div>
</template>
import { ref } from 'vue';
import {login} from "@/util/request";
import {filterMenus, initRouter} from "@/util/routeUtil";
import router from "@/router";
export default {
name:'Login',
setup() {
const user = ref({
username: 'admin',
password: '123456',
});
const rules = {
username: [
{ required: true, message: '请输入用户名', trigger: 'blur' },
],
password: [
{ required: true, message: '请输入密码', trigger: 'blur' },
],
};
function userLogin(){
login(user.value).then(res => {
console.log('login res',res)
if (res.data.message='登录成功'){
//1、初始化路由
initRouter(res.data.data.role.menus)
localStorage.setItem('navMenus',JSON.stringify(filterMenus(res.data.data.role.menus)))
localStorage.setItem('menus',JSON.stringify(res.data.data.role.menus))
localStorage.setItem('token',res.data.data.token)
//2、跳转到主页
router.replace('/index')
}
})
}
return {
user,
rules,
userLogin,
};
},
};
<style>
.login-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.login-card {
width: 400px;
padding: 20px;
}
.login-title {
text-align: center;
margin-bottom: 20px;
}
.login-form {
margin-top: 20px;
}
</style>
欢迎转载,转载请标注出处。关注公众号: JAVA大师, 后台回复 资源,既可获取资源链接 !!!