feat: 添加登录和获取用户信息接口,整合pinia实现用户状态全局共享

This commit is contained in:
ray
2024-09-23 08:29:44 +08:00
parent f106f84646
commit 737f6a3ee5
21 changed files with 6997 additions and 5061 deletions

40
src/pages/login/index.vue Normal file
View File

@@ -0,0 +1,40 @@
<template>
<view class="flex-col items-center">
<input v-model="username" placeholder="请输入用户名" />
<input v-model="password" placeholder="请输入密码" type="password" />
<button class="mt-5" @click="handleLogin">登录</button>
</view>
</template>
<script lang="ts" setup>
import { useUserStore } from "@/store/modules/user";
// 登录表单
const username = ref("admin");
const password = ref("123456");
// 使用 pinia
const userStore = useUserStore();
// 登录处理
const handleLogin = async () => {
await userStore.login(username.value, password.value);
if (!!userStore.token) {
await userStore.getUserInfo(); // 登录成功后获取用户信息
uni.showToast({ title: "登录成功", icon: "success" });
uni.navigateBack(); // 登录成功后返回上一页
} else {
uni.showToast({ title: "登录失败", icon: "none" });
}
};
</script>
<style scoped>
input {
width: 80%;
padding: 10px;
margin-top: 16px;
border: 1px solid #ccc;
}
</style>

View File

@@ -1,5 +0,0 @@
<template>
<view class="flex-center flex-col">
<text class="text-blue font-bold text-lg">我的</text>
</view>
</template>

View File

@@ -0,0 +1,39 @@
<template>
<view class="flex-center flex-col">
<text class="text-blue font-bold text-lg">我的</text>
<!-- 判断是否已登录 -->
<template v-if="isLoggedIn">
<image :src="userInfo?.avatar" class="w100 h100 mb-5 rounded-full" />
<text class="text-lg font-bold">{{ userInfo?.nickname }}</text>
<button @click="handleLogout" class="mt-5">退出登录</button>
</template>
<!-- 未登录时显示去登录按钮 -->
<template v-else>
<text>您还未登录请先登录</text>
<button @click="goToLoginPage" class="mt-5">去登录</button>
</template>
</view>
</template>
<script lang="ts" setup>
import { useUserStore } from "@/store/modules/user";
// 使用 pinia
const userStore = useUserStore();
const isLoggedIn = computed(() => userStore.token);
const userInfo = computed(() => userStore.userInfo);
// 跳转到登录页面
const goToLoginPage = () => {
uni.navigateTo({ url: "/pages/login/index" });
};
// 退出登录处理
const handleLogout = async () => {
await userStore.logout();
uni.showToast({ title: "已退出登录", icon: "success" });
};
</script>