文章目录
- 使用多个独立的 Store来分割模块
- 示例
- auth 模块
- profile 模块
- 在组件中使用
- 共享状态和组合 store
- 总结
在
Pinia
中,已去除
mutations,modules<模块分割>
,只有
state,getters,actions
。虽然没有直接的
modules
概念,但我们可以通过创建多个独立的
store
并在需要时进行组合来实现类似的模块化结构。
使用多个独立的 Store来分割模块
我们可以为每个模块创建独立的 store
,然后在组件中分别引入和使用这些 store
。
示例
假设我们有两个模块:auth
模块和 profile
模块。我们可以分别为它们创建独立的 store
。
auth 模块
// stores/auth.ts
import { defineStore } from 'pinia'interface AuthState {token: string | null;isAuthenticated: boolean;
}export const useAuthStore = defineStore('auth', {state: (): AuthState => ({token: null,isAuthenticated: false,}),actions: {login(token: string) {this.token = tokenthis.isAuthenticated = true},logout() {this.token = nullthis.isAuthenticated = false},},
})
profile 模块
// stores/profile.ts
import { defineStore } from 'pinia'interface ProfileState {name: string;email: string;
}export const useProfileStore = defineStore('profile', {state: (): ProfileState => ({name: '',email: '',}),actions: {setProfile(name: string, email: string) {this.name = namethis.email = email},clearProfile() {this.name = ''this.email = ''},},
})
在组件中使用
在 Vue 组件中,我们可以分别引入和使用这些 store。
<script lang="ts" setup>
import { useAuthStore } from '@/stores/auth'
import { useProfileStore } from '@/stores/profile'const authStore = useAuthStore()
const profileStore = useProfileStore()// 使用 authStore 和 profileStore 的状态和方法
authStore.login('some-token')
profileStore.setProfile('John Doe', 'john.doe@example.com')console.log(authStore.isAuthenticated) // true
console.log(profileStore.name) // 'John Doe'
</script>
共享状态和组合 store
如果我们需要在不同的 store
之间共享状态或方法,可以通过组合的方式来实现。
例如,在上面的 auth
和 profile
store 中,如果需要在登录时更新个人资料,我们可以这样做:
// stores/auth.ts
import { defineStore } from 'pinia'
import { useProfileStore } from '@/stores/profile'interface AuthState {token: string | null;isAuthenticated: boolean;
}export const useAuthStore = defineStore('auth', {state: (): AuthState => ({token: null,isAuthenticated: false,}),actions: {login(token: string) {this.token = tokenthis.isAuthenticated = true// 假设我们在登录时也更新个人资料const profileStore = useProfileStore()profileStore.setProfile('John Doe', 'john.doe@example.com')},logout() {this.token = nullthis.isAuthenticated = false// 在登出时清空个人资料const profileStore = useProfileStore()profileStore.clearProfile()},},
})
总结
在 Pinia
中,通过定义多个独立的 store 并在需要时组合使用,可以实现类似于 Vuex modules
的模块化管理。
参考官网:https://pinia.vuejs.org/zh/introduction.html
如果你在web前端开发、面试、前端学习路线有困难可以在下方加我名片。免费答疑,行业深潜多年的技术牛人帮你解决bug。
可提供web前端开发,网站开发、技术咨询、答疑、直播讲座等服务。
祝你能成为一名优秀的WEB前端开发工程师!