Pinia 是 Vue 的专属状态管理库,它允许你跨组件或页面共享状态。
参考:Pinia 官方文档
# 1. 安装依赖
# 2. main.ts
引入 pinia
| |
| import { createPinia } from "pinia"; |
| import App from "./App.vue"; |
| |
| createApp(App).use(createPinia()).mount("#app"); |
# 3. 定义 Store
根据 Pinia 官方文档 - 核心概念 描述 ,Store 定义分为 选项式
和 组合式
,先比较下两种写法的区别:
选项式 Option Store | 组合式 Setup Store |
---|
| |
至于如何选择,官方给出的建议 : 选择你觉得最舒服的那一个就好
。
这里选择组合式,新建文件 src/store/counter.ts
| |
| import { defineStore } from "pinia"; |
| |
| export const useCounterStore = defineStore("counter", () => { |
| |
| const count = ref(0); |
| |
| const double = computed(() => { |
| return count.value * 2; |
| }); |
| |
| function increment() { |
| count.value++; |
| } |
| |
| return { count, double, increment }; |
| }); |
# 4. 父组件
| |
| <script setup lang="ts"> |
| import HelloWorld from "@/components/HelloWorld.vue"; |
| import { useCounterStore } from "@/store/counter"; |
| |
| const counterStore = useCounterStore(); |
| </script> |
| |
| <template> |
| <h1 class="text-3xl">vue3-element-admin-父组件</h1> |
| <el-button type="primary" @click="counterStore.increment">count++</el-button> |
| <HelloWorld /> |
| </template> |
# 5. 子组件
| |
| <script setup lang="ts"> |
| import { useCounterStore } from "@/store/counter"; |
| const counterStore = useCounterStore(); |
| </script> |
| |
| <template> |
| <el-card class="text-left text-white border-white border-1 border-solid mt-10 bg-[#242424]" > |
| <template #header> 子组件 HelloWorld.vue</template> |
| <el-form> |
| <el-form-item label="数字:"> </el-form-item> |
| <el-form-item label="加倍:"> </el-form-item> |
| </el-form> |
| </el-card> |
| </template> |
# 6. 效果预览