What is pinia? how to use? This article will take you to learn about Vue's new generation state management library - Pinia. I hope it will be helpful to you!
After the official version of Vue 3 was released in September 2020, Vuex also released the 4.0 version adapted to Vue 3 in February 2021, but At the end of August 2021, the new Vue state shared library mainly contributed by Vue core team member Eduardo released version 2.0, and in November of the same year, Youda officially designated Pinia as the official state library of Vue (now Vue The official website has also replaced Vuex with Pinia). (Learning video sharing: vue video tutorial)
Pinia is the same as Vuex, it is the " state of Vue Repository " is used to realize cross-page/component form of data state sharing.
In the normal development process, Vue components can pass messages between components through Props and Events. For cross-level components, you can also use EventBus to achieve communication. However, in large projects, it is usually necessary to save a variety of data and status in the browser, and using Props/Events or EventBus is difficult to maintain and expand. . Hence Vuex and Pinia.
mutations. Because in the eyes of most developers, mutations only support synchronous modification of state data, and although actions supports asynchronous, mutations still need to be called internally to modify the state. , is undoubtedly very cumbersome and redundant
type inference as much as possible, and Unlike Vuex, which requires a custom TS wrapper to support TypeScript
Unlike Vuex, which requires injecting state dependencies on the instance/Vue prototype, instead Directly introduce the status module and call the getter/actions function to complete the status update and get; and because of its good support for TypeScript and type inference, developers can enjoy excellent code prompts
No need to pre-register status data, by default it is automatically processed according to code logic; and new status can be registered at any time during use
There is no nested module structure of Vuex, and all states are managed flatly. It can also be understood that the status registered by pinia is similar to the module of vuex, except that pinia does not need a unified entrance to register all status modules
Mutual references and nesting between each state
To summarize:Pinia has improved the state storage structure on the premise of realizing the function of Vuex global state sharing. It optimizes usage and simplifies API design and specification; and based on TypeScript type inference, it provides developers with good TypeScript support and code tips.
As for the installation of Pinia in the project, everyone should know that you can install it directly through the package management tool .
main.ts Registration for Pinia can be completed.
import { createApp } from 'vue' import { createPinia } from 'pinia' const app = createApp(App) const pinia = createPinia() app.use(pinia)
Of course, because createApp supportsAt this time,chain calling, it can also be written directly as createApp(App).use(createPinia()).mount ('#app')
.
createPinia() creates a root instance, in app.use The instance will be injected into the app, and a app.config.globalProperties.$pinia will be configured to also point to the instance.
status module function through the defineStore method (The reason why it is a function is that the state inside needs to be obtained in the form of a function when called later).
The TypeScript definition of the deineStore function is as follows:function defineStore<Id, S, G, A>(id, options): StoreDefinition<Id, S, G, A> function defineStore<Id, S, G, A>(options): StoreDefinition<Id, S, G, A> function defineStore<Id, SS>(id, storeSetup, options?): StoreDefinition<Id, _ExtractStateFromSetupStore<SS>, _ExtractGettersFromSetupStore<SS>, _ExtractActionsFromSetupStore<SS>> type Id = ID extends string type storeSetup = () => SS type options = Omit<DefineStoreOptions<Id, S, G, A>, "id"> | DefineStoreOptions<Id, S, G, A> | DefineSetupStoreOptions<Id, _ExtractStateFromSetupStore<SS>, _ExtractGettersFromSetupStore<SS>, _ExtractActionsFromSetupStore<SS>>
可以看到该函数最多接收 3个参数,但是我们最常用的一般都是第一种或者第二种方式。这里以 第一种方式 例,创建一个状态模块函数:
// 该部分节选字我的开源项目 vite-vue-bpmn-process import { defineStore } from 'pinia' import { defaultSettings } from '@/config' import { EditorSettings } from 'types/editor/settings' const state = { editorSettings: defaultSettings } export default defineStore('editor', { state: () => state, getters: { getProcessDef: (state) => ({ processName: state.editorSettings.processName, processId: state.editorSettings.processId }), getProcessEngine: (state) => state.editorSettings.processEngine, getEditorConfig: (state) => state.editorSettings }, actions: { updateConfiguration(conf: Partial<EditorSettings>) { this.editorSettings = { ...this.editorSettings, ...conf } } } })
其中的 options 配置项包含三个部分:
注意:getters 的函数定义中 第一个参数就是当前 store 的状态数据 state,而 actions 中的函数参数为 实际调用时传递的参数,可以传递多个,内部通过 this 上下文 直接访问 state 并进行更新。
众所周知,vue 3 最大的亮点之一就是 组合式API(Composition API),所以我们先以组件配合 setup 使用。
import { defineComponent, ref, computed } from 'vue' import { storeToRefs } from 'pinia' import { EditorSettings } from 'types/editor/settings' import editorStore from '@/store/editor' export default defineComponent({ setup(props) { const editor = editorStore() // 直接获取 state 状态 const { editorSettings } = storeToRefs(editor) // 使用 computed const editorSettings = computed(() => editor.editorSettings) // getters const prefix = editor.getProcessEngine // 更新方式 1:调用 actions editorStore.updateConfiguration({}) // 更新方式 2:直接改变 state 的值 editorStore.editorSettings = {} // 更新方式 3:调用 $patch editorStore.$patch((state) => { state.editorSettings = {} }) return { editorStore } } })
这里对以上几种处理方式进行说明:
获取值:
可以通过 解构 获取 state 定义的数据,但是 解构会失去响应式,所以需要用 storeToRefs 重新对其进行响应式处理
通过 computed 计算属性,好处是 可以对 state 中的状态数据进行组合
通过定义的 getters 方法来获取值,这种方式获取的结果本身就是 响应式的,可以直接使用
更新值:
而在传统的 optionsAPI 模式的组件中(也没有配置 setup),Pinia 也提供了与 Vuex 一致的 API:mapState,mapGetters,mapActions,另外还增加了 mapStores 用来访问所有已注册的 store 数据,新增了 mapWritableState 用来 定义可更新状态;也因为 pinia 没有 mutations,所以也取消了 mapMutations 的支持。
mapGetters 也只是为了方便迁移 Vuex 的组件代码,后面依然建议 使用 mapState 替换 mapGetters
<template> <div> <p>{{ settings }}</p> <p>{{ processEngine }}</p> <button @click="updateConfiguration({})">调用 action</button> <button @click="update">调用 mapWritableState</button> </div> </template> <script> import { defineComponent, ref, storeToRefs } from 'vue' import { mapState, mapActions, mapWritableState } from 'pinia' import editorStore from '@/store/editor' export default defineComponent({ computed: { ...mapState(editorStore, { settings: 'editorSettings', processEngine: (state) => `This process engine is ${state.editorSettings.processEngine}` }), ...mapWritableState(editorStore, ['editorSettings']) }, methods: { ...mapActions(editorStore, ['updateConfiguration']), update() { this.editorSettings.processEngine = "xxx" } } }) </script>
mapStores 用来访问 所有已注册 store 状态。假设我们除了上文定义的 editor,还定义了一个 id 为 modeler 的 store,则可以这么使用:
import editor from '@/store/editor' import modeler from '@/store/modeler' export default defineComponent({ computed: { ...mapStores(editor, modeler) }, methods: { async updateAll() { if (this.editorStore.processEngine === 'camunda') { await this.modelerStore.update() } } } })Copy after login其中引用的所有 store,都可以通过 id + 'Store' 的形式在 Vue 实例中访问到。
因为 Pinia 本身是支持各个 store 模块互相引用的,所以在定义的时候可以直接引用其他 store 的数据进行操作。
例如我们这里根据 editor store 创建一个 modeler store
import { defineStore } from 'pinia' import editor from '@/store/editor' export default defineStore('editor', { state: () => ({ element: null, modeler: null }), actions: { updateElement(element) { const editorStore = editor() if (!editorStore.getProcessEngine) { editorStore.updateConfiguration({ processEngine: 'camunda' }) } this.element = element } } })
因为 Pinia 的每个 store 模块都是依赖 vue 应用和 pinia 根实例的,在组件内部使用时因为 Vue 应用和 pinia 根实例肯定都已经是 注册完成处于活动状态中的,所以可以直接通过调用对应的 store 状态模块函数即可。
但是在脱离 store 模块与组件,直接在外部的纯函数中使用时,则需要注意 store 状态模块函数的调用时机。
以官方的示例来看:
import { createRouter } from 'vue-router' const router = createRouter({ // ... }) // ❌ 根据导入的顺序,这将失败 const store = useStore() router.beforeEach((to, from, next) => { // 我们想在这里使用 store if (store.isLoggedIn) next() else next('/login') }) router.beforeEach((to) => { // ✅ 这将起作用,因为路由器在之后开始导航 // 路由已安装,pinia 也将安装 const store = useStore() if (to.meta.requiresAuth && !store.isLoggedIn) return '/login' })
直接在js模块的执行中 直接调用是可能会报错的,因为此时可能在 import router 的时候 还没有调用 createApp 和 createPinia 创建对应的应用实例和 pinia 根实例,所以无法使用。
而在路由导航的拦截器中使用时,因为 路由拦截触发时,应用和 pinia 根实例肯定已经全部实例化完毕,才可以正常使用。
所以 如果是在外部的 hooks 函数或者 utils 工具函数等纯函数模块中使用 store 数据时,最好是定义一个函数方法导出,在组件或者 store 模块中调用该方法,保证此时能正确执行
总的来说,Pinia 作为 Vue 官方推荐的状态库,配合 Vue 3 的组合式 API,可以更好的实现项目中各种数据状态的管理,而不是像以前使用 Vuex 一样通过 modules 的形式注册各种状态。Pinia 对于抽离逻辑进行复用(hooks),简化使用方式来说,比之前的 Vuex 好了很多倍;加上良好的类型支持与代码提示,让我们在开发过程中可以省去很多前置工作,也是对我们的开发效率的一种提升吧。
当然,、Vue DevTools 在更新之后,也实现了对 Pinia 的支持。
The above is the detailed content of Detailed explanation of how to use Vue3 state management library Pinia. For more information, please follow other related articles on the PHP Chinese website!