安装 Pinia
步骤 1:安装 Pinia
Pinia 是 Vue 应用的官方状态管理库,用于替代 Vuex。使用以下命令添加 Pinia 依赖:
步骤 2:创建 Pinia 实例
在项目根目录下创建 pinia
文件夹,并在其中新建 index.ts
文件来创建 Pinia
实例:
1import { createPinia } from "pinia"
2export const pinia = createPinia()
步骤 3:创建状态存储
在 pinia/stores
文件夹下新建 app.ts
文件来定义一个状态存储:
1import { defineStore } from 'pinia'
2import { reactive } from 'vue'
3
4export const useAppStore = defineStore('app', () => {
5 // 侧边栏状态
6 const sidebar = reactive({
7 opened: false
8 })
9
10 // 切换侧边栏
11 const toggleSidebar = () => {
12 sidebar.opened = !sidebar.opened
13 }
14
15 return { sidebar, toggleSidebar }
16})
步骤 4:在项目中注册 Pinia
在 main.ts
文件中引入并注册 Pinia
实例:
1// core
2import { createApp } from "vue"
3import { router } from "@/router"
4import { pinia } from "@/pinia" // [!code focus]// [!code ++]
5import App from "./App.vue"
6
7// 创建应用实例
8const app = createApp(App)
9
10// 挂载路由和状态管理 // [!code focus]// [!code ++]
11app.use(router).use(pinia) // [!code focus]// [!code ++]
12
13// router 准备就绪后挂载应用
14router.isReady().then(() => {
15 app.mount("#app")
16})
步骤 5:在组件中使用 Pinia
在 Vue 组件中使用 counter
store:
1<template>
2 <div>
3 <p>状态: {{ appStore.sidebar.opened }}</p>
4 <button @click="appStore.toggleSidebar">切换</button>
5 </div>
6</template>
7
8<script setup>
9import { useAppStore } from '@/pinia/stores/app.ts'
10
11// 使用 Pinia store
12const appStore = useAppStore()
13</script>
通过这些步骤,你可以在 Vue 组件中轻松管理状态。