一、修改Mock接口
新增用户数据userInfo
// mock/login.ts......export default [ { ...... response: ({ body }) => { return { ...... data: { // query: body, token: Mock.Random.string('lower', 200), // 用户信息 userInfo: { id: Mock.Random.id(), name: Mock.Random.cname(), email: Mock.Random.email(), gender: Mock.Random.natural(1, 2), age: Mock.Random.natural(18, 30), }, }, }; }, },];
二、store模块新增user
新增用户信息模块
// src/store/modules/user.tsconst user = { namespaced: true, state: { token: localStorage.getItem('token') || '', userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'), }, getters: {}, mutations: { setToken(state, token) { localStorage.setItem('token', token); state.token = token; }, setUserInfo(state, userInfo) { localStorage.setItem('userInfo', JSON.stringify(userInfo)); state.userInfo = userInfo; }, clearToken(state) { localStorage.removeItem('token'); state.token = ''; }, clearUser(state) { localStorage.removeItem('userInfo'); state.userInfo = {}; }, }, actions: {},};
export default user;
2. 添加模块至store
// src/store/index.ts ...... import user from '@/store/modules/user'; ......
export default createStore({ ...... modules: { loading, user, }, });
## 三、修改登录页功能1. 加入用户信息存储```js// src/views/Login/index.vue......import { useStore } from 'vuex';............setup() { ...... const router = useRouter(); const store = useStore(); ...... const onSubmit = () => { loginFormRef.value.validate().then(() => { LoginAPI.setLogin(toRaw(loginForm)).then((res) => { console.log(res); store.commit('user/setToken', res.token); store.commit('user/setUserInfo', res.userInfo); router.push({ path: '/' }); }); }); }; ......}......
四、修改请求封装
修改token加入header
//src/request/http.ts
...... const Fetch = ({ ...... }: AxiosConfig) => { ...... if (localStorage.getItem('token')) { Object.assign(headers, { token: localStorage.getItem('token'), }); } ...... }; ......
## 五、新增路由拦截1. 登录状态才能进入其他页面2. 非登录状态只能进入登录页面
// src/router/index.ts
...... import store from '@/store';
const routes = [ ...... ];
const router = createRouter({ ...... });
router.beforeEach((to, from, next) => { if (to.name !== 'Login' && !localStorage.getItem('token')) { next({ name: 'Login' }); } else { next(); } });
export default router;
## 六、源代码地址```txthttps://github.com/jiangzetian/vue3-admin-template
七、视频演示及源码
本文演示视频:点击浏览
更多前端内容欢迎关注公众号:天小天个人网
原文:https://juejin.cn/post/7098350837344731149