快速入门 Pinia 状态管理库

前端精髓

共 1733字,需浏览 4分钟

 · 2021-10-27

Pinia 是一个用于 Vue 的状态治理库,相似 Vuex, 是 Vue 的另一种状态治理计划。如果你现在使用 vue3 开发项目,那么推荐你使用 Pinia 开发。


Pinia的优点


1、完整的 TypeScript 支持:与在 Vuex 中添加 TypeScript 相比,添加 TypeScript 更容易。


2、极其轻巧(体积约 1KB)


3、store 的 action 被调度为常规的函数调用,而不是使用 dispatch 方法或 MapAction 辅助函数,这在 Vuex 中很常见。


4、支持多个Store,Pinia 不支持嵌套存储。相反,它允许你根据需要创建 store。但是,store 仍然可以通过在另一个 store 中导入和使用 store 来隐式嵌套。


5、支持 Vue devtools、SSR 和 webpack 代码拆分


快速开始

npm install pinia


创建一个 pinia 作为 root store 添加到 app 中。

import { createApp } from 'vue'import { createPinia } from 'pinia'
const app = createApp({})app.use(createPinia())


开始定义 store

export const useStore = defineStore('main', {  state: () => ({    counter: 0,  }),  getters: {    doubleCount: (state) => state.counter * 2,  },  actions: {    increment() {      this.counter++    },    randomizeCounter() {      this.counter = Math.round(100 * Math.random())    },  },})


在组件中使用 store 。

<template>  <div>    {{store.count}}  div>template>
<script>import { useStore } from '@/stores/counter'
export default { setup() { const store = useStore()
return { // 可以返回 store 实例在模板中使用 store, } },}script>


同样也支持之前的辅助函数。可以使用 mapState 来映射我们 store 中的 state 和 getter。也可以使用 mapActions 来映射 action 函数。

import { mapState } from 'pinia'
export default { computed: { ..mapState(useStore, ['counter', 'doubleCount']) }, methods: { ...mapActions(useStore, ['increment']) ...mapActions(useStore, { myOwnName: 'randomizeCounter' }), },}


Pinia 相比 Vuex 更加简略,而且 Pinia 能够自在扩大。


Pinia 是合乎直觉的状态治理形式,让使用者回到了模块导入导出的原始状态,使状态的起源更加清晰可见。


Pinia 的应用感触相似于 Recoil,但没有那么多的概念和 API,主体十分精简,极易上手(Recoil 是 Facebook 官网出品的用于 React 状态治理库,应用 React Hooks 治理状态)。


而且 Pinia 适用于 Vue 2 和 Vue 3,并且不要求您使用 composition API。

浏览 89
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报