状态管理

基于组合式 API 做状态管理,需要 Pinia 时自行安装。

模板默认不含状态管理库。简单的共享状态用组合式 API 就够,需要完整的状态管理能力时再自行安装 Pinia。

用组合式 API 管理状态

src/composables 目录用来放组合式函数。模板自带 use-count.ts 作为示例。

src/composables/use-count.ts
import { ref } from 'vue'

export function useCount() {
  const count = ref(Math.round(Math.random() * 20))

  function inc() {
    count.value += 1
  }
  function dec() {
    count.value -= 1
  }

  return {
    count,
    inc,
    dec,
  }
}

在页面里显式导入使用:

src/pages/index.vue
<script setup lang="ts">
import { useCount } from '@/composables/use-count'

const { count, inc, dec } = useCount()
</script>

<template>
  <view>
    <button @click="dec">
      -
    </button>
    <text>{{ count }}</text>
    <button @click="inc">
      +
    </button>
  </view>
</template>

模块级的 ref 在多个页面之间共享,函数级的 ref 每次调用都新建。需要全局状态时,把 ref 写在函数外面。

src/composables/use-auth.ts
import { computed, ref } from 'vue'

// 函数外面,全局共享
const token = ref('')

export function useAuth() {
  const isLogin = computed(() => !!token.value)

  function login(next: string) {
    token.value = next
  }

  function logout() {
    token.value = ''
  }

  return { token, isLogin, login, logout }
}

安装 Pinia

Pinia 是 Vue 官方推荐的状态管理库。模板不带它,需要自己安装:

pnpm i pinia

装好后在 src/main.ts 里注册:

src/main.ts
import { createPinia } from 'pinia'
import { createSSRApp } from 'vue'
import App from './App.vue'

export function createApp() {
  const app = createSSRApp(App)
  app.use(createPinia())
  return { app }
}

定义和使用 store:

src/stores/counter.ts
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)

  function increment() {
    count.value++
  }

  return { count, increment }
})
src/pages/index.vue
<script setup lang="ts">
import { useCounterStore } from '@/stores/counter'

const counterStore = useCounterStore()
</script>

<template>
  <view>
    <text>{{ counterStore.count }}</text>
    <button @click="counterStore.increment">
      +1
    </button>
  </view>
</template>

用 VueUse 做持久化

模板已安装 @vueuse/core。可以用 createGlobalState 配合 useStorage 把状态存进 uni-app 的 Storage。

src/utils/uni-storage.ts
export const uniStorage = {
  getItem(key: string) {
    return uni.getStorageSync(key) || null
  },
  setItem(key: string, value: any) {
    uni.setStorageSync(key, value)
  },
  removeItem(key: string) {
    uni.removeStorageSync(key)
  },
}
src/composables/use-auth.ts
import { createGlobalState, useStorage } from '@vueuse/core'
import { computed } from 'vue'
import { uniStorage } from '@/utils/uni-storage'

export const useAuth = createGlobalState(() => {
  const token = useStorage('token', '', uniStorage)
  const isLogin = computed(() => !!token.value)

  function login(next: string) {
    token.value = next
  }

  function logout() {
    token.value = ''
  }

  return { token, isLogin, login, logout }
})