基于vue3+vite5+pinia+ts写一个登录功能,要有登录校验,登录成功后设置Token
时间: 2024-09-29 17:06:10 浏览: 68
vue3+ts+vuerouter+pinia+elementplus+ts环境模板搭建及vite打包优化
5星 · 资源好评率100%
基于Vue 3、Vite 5、Pinia 和 TypeScript 构建一个登录功能,你可以按照以下步骤进行:
1. **设置项目依赖**:
首先你需要安装必要的依赖:
```
npm install -D vite@latest vite-plugin-vue2 typescript pinia vuex-persistedstate axios
```
2. **初始化项目骨架**:
使用Vite初始化项目,并启用TypeScript支持:
```
vite create my-app --template @vitejs/app --type ts
```
3. **创建store和pinia**:
在`src/store`目录下创建`auth.js`,用Pinia管理登录状态和token:
```javascript
import { defineStore } from "pinia";
export const useAuthStore = defineStore("auth", {
state: () => ({
username: "",
password: "",
isLoggedIn: false,
token: null,
}),
actions: {
async login({ username, password }) {
try {
// 模拟API请求,实际应用中应调用真正的API服务
const response = await fetch("/api/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ username, password }),
});
const data = await response.json();
if (data.success) {
this.isLoggedIn = true;
this.token = data.token; // 存储token
} else {
this.errorMessage = data.message;
}
} catch (error) {
console.error("Error logging in:", error);
}
},
logout() {
this.isLoggedIn = false;
this.token = null;
},
},
getters: {
isLoggedIn() {
return this.isLoggedIn;
},
},
});
```
4. **更新登录组件**:
```html
<template>
...
<button @click="handleSubmit">登录</button>
...
</template>
<script lang="ts">
import { computed, watch } from 'vue';
import { useAuthStore } from "@/store/auth";
export default {
setup() {
const authStore = useAuthStore();
const { username, password, isLoggedIn, errorMessage } = authStore;
// 添加登录校验和提交逻辑
const handleSubmit = async () => {
if (!username || !password) {
authStore.errorMessage = "请输入用户名和密码";
return;
}
await authStore.login({ username, password });
// 如果登录成功,可以在其他组件通过props获取token
// 并使用axios添加Authorization头
if (authStore.isLoggedIn) {
// 例如:
// window.localStorage.setItem("token", authStore.token);
// 在axios拦截器中设置token
// const axiosInstance = axios.create({
// baseURL: process.env.VUE_APP_API_URL,
// withCredentials: true,
// headers: { Authorization: `Bearer ${authStore.token}` },
// });
// axiosInstance.interceptors.request.use((config) => {
// config.headers.Authorization = `Bearer ${authStore.token}`;
// return config;
// });
}
};
// 登出逻辑
function logout() {
authStore.logout();
}
return {
username,
password,
isLoggedIn: computed(authStore.isLoggedIn),
errorMessage,
handleSubmit,
logout,
};
},
};
</script>
```
5. **在路由守卫中验证token**:
创建一个全局守卫如`router.ts`中检查是否有token:
```javascript
import { RouteGuard, useRouter } from "@vue-router/runtime-core";
import { useAuthStore } from "@/store/auth";
export const requiresAuth: RouteGuard = async (to, from, next) => {
const router = useRouter();
const authStore = useAuthStore();
if (authStore.isLoggedIn) {
next();
} else {
router.push("/login");
}
};
```
现在你已经实现了基于Vue 3、Vite 5、Pinia和TypeScript的登录功能。当用户登录成功,token会在本地存储并在需要的地方添加至HTTP请求头。
阅读全文