1. 安装 pinia, npm i pinia

2. 在 main.ts 文件中引入 pinia

import { createApp, App } from 'vue'
import { createPinia, Pinia } from 'pinia'
import AppComponent from './App.vue'

const app: App = createApp(AppComponent)
const pinia: Pinia = createPinia()
app.use(pinia)
app.mount('#app')

3. 新建 /src/store 目录存放公共状态文件,例如

3.1 新建 test.type.ts 定义类型
type TestState = {
  count: number
  user: {
    age: number
    name: string
  }
}
type TestGetters = {
  doubleCount: (state: TestState) => number
  username: (state: TestState) => string
}
type TestActions = {
  setCount: (count: number) => void
}
// 注意:如有导入导出的依赖数据或类型,自定义test类型需要使用export导出;否则可视为全局类型即可直接使用
3.2 新建 test.ts 创建test模块公共状态
import { defineStore } from 'pinia'

// 在此约束类型不管编写或使用都可有较好的提示
export const useTestStore = defineStore<string, TestState, TestGetters, TestActions>('TestId', {
  state: () => ({
    count: 10,
    user: {
      age: 18,
      name: '小明'
    }
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
    username: (state) => state.user.name
  },
  actions: {
    setCount(count: number) {
      this.count = count
    }
  }
})

4. 最后在任意页面使用即可

<script setup lang="ts">
import { useTestStore } from '@/store/test' 

const testStore = useTestStore()
console.log(testStore.count)
console.log(testStore.user.name)
console.log(testStore.doubleCount)
console.log(testStore.username)

// 修改state数据方式1
testStore.count = 11
testStore.$state.count = 11

// 修改state数据方式2
testStore.$patch({
  count: 11
})
testStore.$patch(state => {
  state.count = 11
})

// 修改state数据方式3(不建议)
testStore.$state = {
  count: 11
}

// 修改state数据方式4(建议)
testStore.setCount(11)

</script>

版权声明:本文为qq_41577134原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_41577134/article/details/127398960