快速入门 Pinia 状态管理库

173819e984f163df503a671ce9e97499.png

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。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值