Skip to main content

基础使用

详细文档:https://pinia.vuejs.org/zh/core-concepts/

基础架构

常用目录: src/store

DIR:                                                 # 项目目录
|-- src/ # 「src」
| |-- stores/ # 「pina目录」
| | |-- ns/ # 「子目录」
| | | `-- index.ts #
| `-- index.ts #

基础语法

import { defineStore } from "pinia"

export const useGlobalStore = defineStore("global", {
state: () => ({
settingPageShow: false,
settingPageSelect: "global" as SettingPageValue,

currtPage: "ImageCuter" as PagesType,
DEBUG: false,
}),

getters: {
currtSettingPage(state) {
return state.settingPageSelect
},
},

actions: {
setSettingPageShow(flag: boolean) {
this.settingPageShow = flag
},
switchSettingPage(pageKey: SettingPageValue = SettingPageValue.GLOBAL) {
this.settingPageShow = true
this.settingPageSelect = pageKey
},
},
})

通讯方式

不同的状态实例通讯方式如下

场景1 - 两个 Store

假设有两个 Store,userStoresettingsStore

// userStore.ts
import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
state: () => ({
name: 'Alice',
age: 25,
}),
actions: {
updateName(newName: string) {
this.name = newName;
},
},
});
// settingsStore.ts
import { defineStore } from 'pinia';
import { useUserStore } from './userStore';

export const useSettingsStore = defineStore('settings', {
state: () => ({
theme: 'light',
}),
actions: {
getUserInfo() {
const userStore = useUserStore(); // 引用 userStore
console.log(`User: ${userStore.name}, Age: ${userStore.age}`);
},
updateUserName(newName: string) {
const userStore = useUserStore(); // 调用 userStore 的方法
userStore.updateName(newName);
},
},
});

依赖注入式互相调用(推荐)

// userStore.ts
import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
state: () => ({
name: 'Alice',
age: 25,
}),
});

// settingsStore.ts
import { defineStore } from 'pinia';
import { useUserStore } from './userStore';

export const useSettingsStore = defineStore('settings', {
state: () => ({
theme: 'light',
}),
actions: {
injectUserStore(userStore: ReturnType<typeof useUserStore>) {
console.log(`Injected User: ${userStore.name}`);
},
},
});

// 使用时
import { useUserStore } from './stores/userStore';
import { useSettingsStore } from './stores/settingsStore';

const userStore = useUserStore();
const settingsStore = useSettingsStore();

settingsStore.injectUserStore(userStore); // 通过参数显式传递

组件中同时使用多个 Store

在组件中,可以通过 useStore 调用多个 store,并根据需要进行状态读取或方法调用。

<script setup lang="ts">
import { useUserStore } from './stores/userStore';
import { useSettingsStore } from './stores/settingsStore';

const userStore = useUserStore();
const settingsStore = useSettingsStore();

function changeThemeAndUserName() {
settingsStore.theme = 'dark'; // 修改 settingsStore 的状态
userStore.updateName('Bob'); // 修改 userStore 的状态
}
</script>

<template>
<div>
<p>User: {{ userStore.name }}</p>
<p>Theme: {{ settingsStore.theme }}</p>
<button @click="changeThemeAndUserName">Change Theme and User Name</button>
</div>
</template>