|
这里或许是互联网从业者的最后一片净土,随客社区期待您的加入!
您需要 登录 才可以下载或查看,没有账号?立即注册
×
本帖最后由 zzz 于 2025-7-10 17:29 编辑
安装
- yarn add pinia 或 npm install pinia
复制代码 注册 Pinia- import { createPinia } from 'pinia'
- app.use(createPinia())
复制代码
通过defineStore 创建 Store- import { defineStore } from 'pinia'
- export const useUserStore = defineStore("main", {
- });
复制代码 state- import { defineStore } from 'pinia'
- const useStore = defineStore('mian', {
- // 推荐使用 完整类型推断的箭头函数
- state: () => {
- return {
- // 所有这些属性都将自动推断其类型
- counter: 0,
- name: 'Eduardo',
- isAdmin: true,
- }
- },
- })
复制代码 action- export const useStore = defineStore('main', {
- state: () => ({
- counter: 0,
- }),
- actions: {
- increment() {
- this.counter++
- },
- randomizeCounter() {
- this.counter = Math.round(100 * Math.random())
- },
- },
- })
复制代码
getters- export const useStore = defineStore('main', {
- state: () => ({
- counter: 0,
- }),
- getters: {
- doubleCount: (state) => state.counter * 2,
- },
- })
复制代码
创建具体 Store(组合式 API )- import { defineStore } from 'pinia',
- const useCounterStore = defineStore('counterStore', {
- state: () => ({
- counter: 0
- })
- })
复制代码
使用 Store- <script setup>
- import { useCounterStore } from "@/stores/counter";
- // 注意:这里导入的函数,不能被解构,那么会失去响应式。
- // 例如不能这样: const { count } = useCounterStore();
- const counterStore = useCounterStore();
- </script>
复制代码 读取state- const store = useStore()
- store.counter++
复制代码 修改 state- store.$patch({
- counter: store.counter + 1,
- name: 'Abalam',
- })
复制代码 重置 state- const store = useStore()
- store.$reset()
复制代码 替换 state
- store.$state = { counter: 666, name: 'Paimon' }
复制代码
|
|