Vue状态管理器之Pinia
本文最后更新于 419 天前,其中的信息可能已经有所发展或是发生改变。

Pinia 使用

随着 Vue3 的逐步推广,状态管理可以利用响应式函数实现简单的 hook 管理全局变量。但是可以考虑使用一个更加简单的方法更高效、有序的管理,那就是 pinia。Vue 官方也将推荐状态管理库由 Vuex 更新为 Pinia


什么是 Pinia

Intuitive, type safe and flexible Store for Vue(直观、类型安全且灵活的 Vue 状态管理器)

与 Vuex 有什么区别

相同点

  • 都是 Vue 的状态管理器
  • 都是响应式的数据
  • 都支持同步、异步修改数据
  • 都是安全的数据管理器

不同点

pinia

  • 更加轻量的状态管理器;更加简单的使用方式;更加直观的数据管理方式
  • 没有 Mutations 概念,减少心智负担
  • 纯 TypeScript 设计,完全满足 TypeScript 开发者的使用体验
  • 支持多个 Store

vuex

  • 支持调试功能,如时间旅行和编辑

为什么推荐使用 Pinia

简单的使用方式,是个人推荐的最大理由,话不多说上示例


安装 Pinia

yarn add pinia
# or with npm
npm install pinia

注册 Pinia

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const pinia = createPinia()
const app = createApp(App)

app.use(pinia)
app.mount('#app')

创建 Store(这里只举例:Setup Stores)

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const name = ref('Eduardo')
  const doubleCount = computed(() => count.value * 2)
  function increment() {
    count.value++
  }

  return { count, name, doubleCount, increment }
})

页面引入使用

import { useCounterStore } from '@/stores/counter'

export default {
  setup() {
    const store = useCounterStore()

    return {
      // you can return the whole store instance to use it in the template
      store,
    }
  },
}

如何选择状态管理器

如果大家已经上手 vue3 了,个人建议直接在初始化工程时使用 pinia 。如果是 typescript 开发者,不想体验麻烦的 vuex 的类型问题,也可以直接选择体验一番。祝大家开发愉快

【版权声明】
本文首发于云博客,欢迎转载,但是必须保留本文的署名云博客(包含链接)。
如您想成为本站的作者或者编辑,请给我留言:yun@yka.moe
本文永久链接:Vue状态管理器之Pinia
本文作者:ray
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇