Selaa lähdekoodia

refactor(store): 改为使用store存储静态数据

laiqi 1 vuosi sitten
vanhempi
commit
994fd42d80

+ 3 - 2
src/App.vue

@@ -1,13 +1,14 @@
 <script setup lang="ts">
 import { onLaunch, onShow, onHide } from '@dcloudio/uni-app'
 import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'
+import { useAppStore } from '@/store/app'
 
 onLaunch(() => {
   console.log('App Launch')
   // 检查是否已登录
-  const loginInfo = uni.getStorageSync('loginInfo')
+  const appStore = useAppStore()
 
-  if (!(loginInfo && loginInfo.token)) {
+  if (!appStore.isLogined) {
     uni.navigateTo({ url: '/pages-sub/auth/index' })
   }
 })

+ 3 - 3
src/interceptors/route.ts

@@ -4,15 +4,15 @@
  * 可以设置路由白名单,或者黑名单,看业务需要选哪一个
  * 我这里应为大部分都可以随便进入,所以使用黑名单
  */
-import { useUserStore } from '@/store'
+import { useAppStore } from '@/store'
 import { needLoginPages as _needLoginPages, getNeedLoginPages } from '@/utils'
 
 // TODO Check
 const loginRoute = '/pages/login/index'
 
 const isLogined = () => {
-  const userStore = useUserStore()
-  return userStore.isLogined
+  const appStore = useAppStore()
+  return appStore.isLogined
 }
 
 const isDev = import.meta.env.DEV

+ 6 - 2
src/pages-sub/auth/index.vue

@@ -23,7 +23,11 @@
 import { getAuthCode } from '@/service/auth'
 import { onMounted } from 'vue'
 import { until } from '@vueuse/core'
+import { useAppStore } from '@/store/app'
+import { useUserStore } from '@/store/user'
 
+const userStore = useUserStore()
+const appStore = useAppStore()
 const loading = ref(false)
 
 // 微信登录
@@ -41,7 +45,7 @@ const handleLogin = async () => {
       //   language: ""
       //   nickName: "微信用户"
       //   province: ""
-      uni.setStorageSync('userInfo', userInfo)
+      userStore.setUserInfo(userInfo)
 
       // 获取token
       uni.login({
@@ -59,7 +63,7 @@ const handleLogin = async () => {
             if (!error.value && data.value) {
               const { token, userid, openid } = data.value as any
 
-              uni.setStorageSync('loginInfo', { token, userid, openid })
+              appStore.setAppInfo({ token, userid, openid })
 
               uni.switchTab({ url: '/pages/index/index' })
             } else {

+ 4 - 2
src/pages/index/index.vue

@@ -19,7 +19,7 @@
       :list="swiperList"
       autoplay
       v-model:current="current"
-      :indicator="{ type: 'dots-bar' }"
+      :indicator="{ type: 'dots-bar' } as any"
       @click="handleSwiperClick"
       @change="handleSwiperChange"
     ></wd-swiper>
@@ -28,8 +28,10 @@
       <!-- 网点地址标题 -->
       <view class="text-lg font-bold py-4 border-b border-gray-100">农机销售网点</view>
 
+      <wd-status-tip image="comment" tip="暂无数据" v-if="locationList.length === 0" />
+
       <!-- 网点列表 -->
-      <view class="divide-y divide-gray-100">
+      <view class="divide-y divide-gray-100" v-else>
         <view
           v-for="(item, index) in locationList"
           :key="index"

+ 14 - 7
src/pages/mine/index.vue

@@ -23,9 +23,9 @@
         </view>
         <view class="ml-4 text-white">
           <view class="text-xl font-bold">
-            {{ userInfo.isLogin ? userInfo.nickName : '未登录' }}
+            {{ isLogin ? userInfo.nickName : '未登录' }}
           </view>
-          <view class="text-sm mt-1 opacity-90" v-if="!userInfo.isLogin">当前游客身份</view>
+          <view class="text-sm mt-1 opacity-90" v-if="!isLogin">当前游客身份</view>
         </view>
       </view>
     </view>
@@ -90,18 +90,25 @@
 </template>
 
 <script lang="ts" setup>
-import { ref } from 'vue'
+import { ref, computed } from 'vue'
+import { useUserStore } from '@/store/user'
+import { useAppStore } from '@/store/app'
+
+const userStore = useUserStore()
+const appStore = useAppStore()
 
 // 用户信息
-const userInfo = ref({
-  isLogin: false,
+const userInfo = ref<Partial<IUserInfo>>({
   avatarUrl: '',
   nickName: '',
 })
 
+const isLogin = computed(() => appStore.isLogined)
+
 onMounted(() => {
-  userInfo.value = uni.getStorageSync('userInfo')
-  userInfo.value.isLogin = uni.getStorageSync('loginInfo')?.token
+  userInfo.value = userStore.userInfo
+
+  console.log('userInfo:', userInfo.value)
 })
 
 // 页面跳转

+ 35 - 0
src/store/app.ts

@@ -0,0 +1,35 @@
+import { defineStore } from 'pinia'
+import { ref } from 'vue'
+
+const initState = { token: '', userid: '', openid: '' }
+
+export const useAppStore = defineStore(
+  'app',
+  () => {
+    const appInfo = ref<IAppInfo>({ ...initState })
+
+    const setAppInfo = (val: IAppInfo) => {
+      appInfo.value = val
+    }
+
+    const clearAppInfo = () => {
+      appInfo.value = { ...initState }
+    }
+    // 一般没有reset需求,不需要的可以删除
+    const reset = () => {
+      appInfo.value = { ...initState }
+    }
+    const isLogined = computed(() => !!appInfo.value.token)
+
+    return {
+      appInfo,
+      setAppInfo,
+      clearAppInfo,
+      isLogined,
+      reset,
+    }
+  },
+  {
+    persist: true,
+  },
+)

+ 1 - 0
src/store/index.ts

@@ -15,3 +15,4 @@ export default store
 
 // 模块统一导出
 export * from './user'
+export * from './app'

+ 10 - 3
src/store/user.ts

@@ -1,7 +1,16 @@
 import { defineStore } from 'pinia'
 import { ref } from 'vue'
 
-const initState = { nickname: '', avatar: '' }
+const initState = {
+  nickName: '',
+  gender: 0,
+  language: '',
+  city: '',
+  province: '',
+  country: '',
+  avatarUrl: '',
+  is_demote: true,
+}
 
 export const useUserStore = defineStore(
   'user',
@@ -19,13 +28,11 @@ export const useUserStore = defineStore(
     const reset = () => {
       userInfo.value = { ...initState }
     }
-    const isLogined = computed(() => !!userInfo.value.token)
 
     return {
       userInfo,
       setUserInfo,
       clearUserInfo,
-      isLogined,
       reset,
     }
   },

+ 14 - 2
src/typings.d.ts

@@ -18,11 +18,23 @@ declare global {
   }
 
   type IUserInfo = {
-    nickname?: string
-    avatar?: string
+    nickName?: string
+    avatarUrl?: string
     /** 微信的 openid,非微信没有这个字段 */
     openid?: string
     token?: string
+    gender?: number
+    language?: string
+    city?: string
+    province?: string
+    country?: string
+    is_demote?: boolean
+  }
+
+  type IAppInfo = {
+    token?: string
+    userid?: string
+    openid?: string
   }
 }
 

+ 45 - 7
src/utils/http.ts

@@ -1,13 +1,18 @@
 import { CustomRequestOptions } from '@/interceptors/request'
+import { useUserStore } from '@/store/user'
+import { useAppStore } from '@/store/app'
 
 export const http = <T>(options: CustomRequestOptions) => {
+  const userStore = useUserStore()
+  const appStore = useAppStore()
+
   // 1. 返回 Promise 对象
   return new Promise<IResData<T>>((resolve, reject) => {
     uni.request({
       ...options,
       header: Object.assign(
         {
-          token: `${uni.getStorageSync('loginInfo')?.token}`,
+          token: `${appStore.appInfo.token}`,
         },
         options.header,
       ),
@@ -17,21 +22,53 @@ export const http = <T>(options: CustomRequestOptions) => {
       // #endif
       // 响应成功
       success(res) {
-        // 状态码 2xx,参考 axios 的设计
+        const { Status, Message, Data } = res.data as any
+
+        // 2. http的状态码 状态码 2xx,参考 axios 的设计
         if (res.statusCode >= 200 && res.statusCode < 300) {
-          // 2.1 提取核心数据 res.data
-          resolve(res.data as IResData<T>)
+          // 3. 业务状态码
+          switch (Status) {
+            case 0: // 请求成功
+              resolve(res.data as IResData<T>)
+              break
+            case -1: // 请求失败
+              uni.showToast({
+                icon: 'none',
+                title: Message || '请求错误',
+                duration: 3000,
+              })
+              break
+            case -2: // token过期
+              // 判断是否已登录
+              if (appStore.isLogined) {
+                uni.showToast({
+                  icon: 'none',
+                  title: Message || '请求错误',
+                  duration: 3000,
+                  success: () => {
+                    userStore.clearUserInfo()
+                    appStore.clearAppInfo()
+                    uni.navigateTo({ url: '/pages-sub/auth/index' })
+                  },
+                })
+              }
+              break
+            default:
+              break
+          }
         } else if (res.statusCode === 401) {
           // 401错误  -> 清理用户信息,跳转到登录页
-          // userStore.clearUserInfo()
-          // uni.navigateTo({ url: '/pages/login/login' })
+          userStore.clearUserInfo()
+          appStore.clearAppInfo()
+          uni.navigateTo({ url: '/pages-sub/auth/index' })
           reject(res)
         } else {
           // 其他错误 -> 根据后端错误信息轻提示
           !options.hideErrorToast &&
             uni.showToast({
               icon: 'none',
-              title: (res.data as IResData<T>).msg || '请求错误',
+              title: (res.data as IResData<T>).Message || '请求错误',
+              duration: 3000,
             })
           reject(res)
         }
@@ -41,6 +78,7 @@ export const http = <T>(options: CustomRequestOptions) => {
         uni.showToast({
           icon: 'none',
           title: '网络错误,换个网络试试',
+          duration: 3000,
         })
         reject(err)
       },