从代码结构和使用方式区分全局状态和局部状态
- 代码结构
- 全局状态:全局状态的store通常在项目的根级别引入和管理,多个组件都可能依赖它。一般会有一个专门的目录(如
stores
目录)来存放全局状态相关的store文件,这些store被所有组件共享。
- 局部状态:局部状态的store往往与特定组件紧密相关,可能会在组件所在目录下定义,甚至直接在组件内部定义(虽然这种情况较少)。它只为特定组件或组件树的一部分服务。
- 使用方式
- 全局状态:在任何组件中都可以通过
useStore
函数获取全局store实例并访问其状态和方法。例如,在多个不同组件中都可能会读取和修改全局用户信息。
- 局部状态:主要由特定组件及其子组件使用,其他无关组件不会涉及。比如一个表格组件内部的展开/折叠状态,仅在该表格组件及其相关子组件中使用。
定义全局状态的store示例
- 创建全局store文件(如
stores/userStore.js
)
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: () => ({
userInfo: null,
token: ''
}),
actions: {
setUserInfo(info) {
this.userInfo = info
},
setToken(token) {
this.token = token
}
}
})
- 在组件中使用
<template>
<div>
<p>用户信息: {{ userStore.userInfo }}</p>
<button @click="setUser">设置用户信息</button>
</div>
</template>
<script setup>
import { useUserStore } from '@/stores/userStore'
const userStore = useUserStore()
const setUser = () => {
userStore.setUserInfo({ name: '张三', age: 20 })
}
</script>
定义局部状态相关的store示例
- 假设在
components/Table.vue
组件相关目录下创建tableStore.js
import { defineStore } from 'pinia'
export const useTableStore = defineStore('table', {
state: () => ({
isExpanded: false
}),
actions: {
toggleExpand() {
this.isExpanded =!this.isExpanded
}
}
})
- 在
Table.vue
组件中使用
<template>
<div>
<button @click="toggleExpand">
{{ isExpanded? '折叠表格' : '展开表格' }}
</button>
</div>
</template>
<script setup>
import { useTableStore } from './tableStore'
const tableStore = useTableStore()
const toggleExpand = () => {
tableStore.toggleExpand()
}
const isExpanded = tableStore.isExpanded
</script>