Pinia不就是Vuex5?

331 阅读2分钟

刚开始使用vue3的时候,全局状态管理器都是使用pinia。还没去了解的时候并不明白为什么要换掉vuex,毕竟是用了好几年的状态管理器,能达到的效果和语法跟vuex几乎一模一样,所以为什么要换?

当时创建模板项目的也没说清楚,就说是vue3团队推荐使用的,大家都在用,那就用吧。其实并不喜欢这样的答案,大家都用那就用。

去官网看看,去Vuex GitHub看看,这不就是vuex5吗,只是换了个名字。

Vuex GitHub:

Pinia is now the new default

The official state management library for Vue has changed to Pinia. Pinia has almost the exact same or enhanced API as Vuex 5, described in Vuex 5 RFC. You could simply consider Pinia as Vuex 5 with a different name. Pinia also works with Vue 2.x as well.

Vuex 3 and 4 will still be maintained. However, it's unlikely to add new functionalities to it. Vuex and Pinia can be installed in the same project. If you're migrating existing Vuex app to Pinia, it might be a suitable option. However, if you're planning to start a new project, we highly recommend using Pinia instead.

你可以简单地将 Pinia 视为具有不同名称的 Vuex 5。所以,相同的团队,相同的功能,就是换个名字。

肯定也有一些人用习惯了某个插件,心里还是有点排斥升级,完全没必要,使用方法几乎一模一样,而且更符合vue3,也兼容vue2.x,所以早点拥抱pinia吧。

个人认为几个比较大的点
  • 少了Mutation,action支持同步异步(用vuex的时候早就发现了mutation没啥用,单纯是为了更好区分同步异步)。
  • 更好的typescript支持,就像antd、element-plus都出了typescript版本。
  • 不用modules了,可以创建多个store,仍然可以通过在另一个store中导入和使用来隐式嵌套store,但Pinia通过设计提供平面结构,同时仍然支持store之间的交叉组合方式。您甚至可以拥有store的循环依赖关系。
  • 支持插件扩展(没用过,还不知道这个特性的意义)。
  • 服务器端渲染支持,对于做SSR是个福音。
  • 提供了 Composition-API 风格的 API。
使用

安装:npm install pinia

main.js注入:

import { createPinia } from "pinia";
const pinia = createPinia();

app.use(pinia);

创建store文件夹,如果分模块就个自新建自己的.ts文件:common.ts、goods.ts,也可以一个文件里面通过不同名字区分:

import { defineStore } from 'pinia'

export const commonStore = defineStore('common', {
    state: () => {
        return {
          name: 'common'
        };
    },
    actions: {
        saveName(name: string) {
            this.name = name;
        },
    },
})

使用:

<template>
  {{ store.name }}
</template>

<script setup lang="ts">
import { commonStore } from "../store/common";
const store = commonStore();

setTimeout(() => {
  store.saveName("wade");
}, 3000);
</script>

跟vuex真的一样,其它使用就不举例了,可以官网好好看看。

倒是几个API可以注意一下:

  • 重置$reset()
  • 批量修改$patch()
  • 替换整个state:store.$state
  • 订阅状态$subscribe()

所以,拥抱大菠萝pinia吧,只是新一代的vuex。

欢迎关注订阅号 coding个人笔记