Browse Source

新增useAuthStore管理登录状态相关

littleblue55 2 months ago
parent
commit
21aa73dc49
4 changed files with 62 additions and 9 deletions
  1. 3 1
      main.js
  2. 29 7
      pages/index/index.vue
  3. 29 0
      store/authStore.js
  4. 1 1
      utils/auth.js

+ 3 - 1
main.js

@@ -14,12 +14,14 @@ app.$mount()
 // #ifdef VUE3
 // 引入uview UI
 import uView from './uni_modules/vk-uview-ui'
-
+import { createPinia } from 'pinia'
 import { createSSRApp } from 'vue'
 export function createApp() {
   const app = createSSRApp(App)
+  const pinia = createPinia()
 	// 使用uView UI
 	app.use(uView)
+	app.use(pinia)
   return {
     app
   }

+ 29 - 7
pages/index/index.vue

@@ -1,22 +1,41 @@
 <template>
 	<view class="container">
-		<view :style="{height: statusBarHeight + 'px'}"></view>
+		<!-- <view :style="{height: statusBarHeight + 'px'}"></view> -->
 		<!-- <view :style="{height: navBarHeight + 'px'}"></view> -->
+		<u-navbar :is-back="false" title="" :background="{ background: '#f7f7f7' }" :border-bottom="false">
+			<view class="slot-wrap">
+				<image src="/static/images/login-icon.png" mode="aspectFit" style="width: 200rpx;"></image>
+			</view>
+		</u-navbar>
 		<view class="page-content">
-			主页
+			<button @click="toPage">是否登录</button>
 		</view>
 	</view>
 </template>
 
 <script setup>
-	import { ref } from 'vue'
-	import { onReady, onLoad } from '@dcloudio/uni-app'
-	
+	import {
+		ref
+	} from 'vue'
+	import {
+		onReady,
+		onLoad
+	} from '@dcloudio/uni-app'
+	import { useAuthStore } from '@/store/authStore'
+	const authStore = useAuthStore()
 	// 屏幕状态栏高度
 	const statusBarHeight = ref(0)
 	// 顶部导航栏高度
 	const navBarHeight = ref(0)
-	
+	const toPage = () => {
+		if(!authStore.isAuthenticated){
+			uni.navigateTo({
+				url: "/pages/login/login"
+			})
+			return
+		}
+		console.log("登陆了")
+	}
 	onReady(() => {
 		uni.getSystemInfo({
 			success(e) {
@@ -41,4 +60,7 @@
 		background-color: $uni-bg-color;
 		padding: 0 20rpx;
 	}
-</style>
+	.slot-wrap{
+		padding-left: 20rpx;
+	}
+</style>

+ 29 - 0
store/authStore.js

@@ -0,0 +1,29 @@
+import { defineStore } from 'pinia'
+import { getToken,setToken,removeToken } from '@/utils/auth.js'
+export const useAuthStore = defineStore('auth', {
+	state: () => ({
+		token: null,
+	}),
+	actions: {
+		setAuthToken(newToken) {
+			this.token = newToken
+			// 可以选择将 token 存储到 localStorage 或 sessionStorage
+			setToken(newToken)
+		},
+		clearAuthToken() {
+			this.token = null
+			removeToken()
+		},
+		loadAuthToken() {
+			const savedToken = getToken()
+			if (savedToken) {
+				this.token = savedToken
+			}
+		}
+	},
+	getters: {
+	    isAuthenticated(state) {
+	      return !!state.token; // 如果 token 存在,返回 true;否则返回 false
+	    }
+	  }
+})

+ 1 - 1
utils/auth.js

@@ -1,4 +1,4 @@
-const TokenKey = 'App-Token'
+const TokenKey = 'token'
 // token
 export function getToken() {
   return uni.getStorageSync(TokenKey)