本文打算谈论以下内容:

  • vuex@4
  • pinia 用法浅析
  • 谈vuex5
  • rfc概念和流程

    Vuex@4

vuex@4 是 vue3 官方的数据管理插件。通过 vuex 我们可以把数据存入 store 中,后续如果要修改有 mutation 和 action 两种方式操作。

以上是事实。虽然会感到冗余,但是操作会得到风格的统一,并且可以在 devtool 中得到相关提示。

  1. // store/index.ts
  2. import { createStore } from "vuex";
  3. const state = () => ({
  4. count: 0
  5. });
  6. const store = createStore({
  7. state() {
  8. return {
  9. count: 0
  10. };
  11. },
  12. mutations: {
  13. inc(state) {
  14. state.count++;
  15. }
  16. }
  17. });
  18. export default store;
  19. // app.vue
  20. const add = () => {
  21. store.commit("inc");
  22. };

image.png
以上就是 vuex@4 的现状了。

需要注意的是:说到底 vuex 只是一个 vue 官方维护的插件,现在有另一个 store 的选择,这就是 pinia 。

Pinia

It was started by Vue core team member Eduardo San Martin Morote with the first commit to the repo being made on Nov 18, 2019. Pinia 是 vue的核心团队成员制作的

基本使用自己翻文档。使用方式大致如下:

  1. // store.js
  2. import { defineStore } from "pinia";
  3. export const useCounterStore = defineStore({
  4. id: "counter",
  5. state: () => ({
  6. count: 0
  7. }),
  8. actions: {
  9. inc() {
  10. this.$state.count++; // 利用this完美解决传参没类型的问题
  11. }
  12. }
  13. });
  14. // app.vue
  15. import { computed, ref } from "vue";
  16. import { useCounterStore } from "@/store/index";
  17. const store2 = useCounterStore();
  18. const counter = computed(() => store2.count); // 下面三种方式都可以改变这个值
  19. // 三种修改方式都可以
  20. const add = () => {
  21. store2.count += 1;
  22. };
  23. const add2 = () => {
  24. store2.$patch({
  25. count: store2.count + 1
  26. });
  27. };
  28. const add3 = () => {
  29. store2.inc();
  30. };

三种修改值的方式都可以,看下图,都能被 devtool 捕捉到!通过 useStore() 获得当前 store ,更是从根本上移除了嵌套模块使用复杂的问题。随用随取,并且 ts 推导更容易。

image.png

使用感受就是舒服!相比之下 vuex 在 ts下还要随时控制类型,难用!

那 pinia 和 vuex4 不就展开竞争力嘛,而且 pinia 作者本身是 vue 里的人,那 pinia 未来会怎样?这就引入了 vuex5 和 RFC

补充:pinia目前已经贡献给了 vuejs 官方,目前的网址为:https://github.com/vuejs/pinia

同时在 create-vue 中,直接把 pinia 推荐为 store 的唯一推荐,相当于官宣扶正了。你可以通过 npm init vue@latest 来看到官网给的最佳实践,这可以作为推广使用 pinia 的核心论点。

RFC

所谓RFC 是request for comments,看起来是一个流程,你对vue有改进想法,比如新功能,就可以往这个仓库里提PR进行讨论,如果感觉还可以,会进入active,集中讨论,如果顺利就会进入试试阶段。之前讨论 ref: 语法糖时候,rfc就被众人熟知。再往前大概就是 functional api 了。

既然有这个流程,翻开 https://github.com/vuejs/rfcs 看到 active 文件夹,和PR就能看到很多东西。这就是未来啊!

翻开pr,就能看到这个 https://github.com/vuejs/rfcs/pull/271 ,里面说有个提案,就可以进入 https://github.com/kiaking/rfcs/blob/vuex-5/active-rfcs/0000-vuex-5.md

这就是 Vuex5 的内容了,继续看下面

Vuex5

进入 https://github.com/kiaking/rfcs/blob/vuex-5/active-rfcs/0000-vuex-5.md

提案内容有 摘要、基础案例、动机等。内容好长好长。参考对比 composition-api 和 setup 语法糖的提案,能大致理解流程和 tc39 差不多,如果你想引入新特性,你需要详细阐释新特性的各种细节。

后续尤雨溪在访谈中提到,对下一代 vuex 的规划还在雏形,pinia 作者作为核心成员,先制作了该工具,同样也算官方推荐。

下图是讨论群的一个截图:

image.png

-1 参考资料