Pinia 的 Setup Stores 语法太香了

前端下午茶

共 2669字,需浏览 6分钟

 ·

2022-11-24 19:09

作者:pany
原文:https://juejin.cn/post/7143504636496855077

关于大菠萝

如果你还不了解 Pinia,那你可以将它理解为 Vuex5(因为 Vuex 5 不会出了),是 Vue3 全家桶成员之一。

这里是它的英文官方文档[1],中文文档好像不是官方的,并且当前翻译的不全面(比如 Setup Stores 就没有在中文文档中出现),不是很推荐。

先来看看最常见的 Option Stores 语法

传递带有 stategettersactions 属性的 Options 对象给 defineStore() 就可以定义一个 Store:

export const useCounterStore = defineStore('counter', {
  state() => ({
    count0
 }),
  getters: {
    doubleCount(state) => state.count * 2
  },
  actions: {
    increment() {
      this.count++
    }
  }
})

这种语法与 Vuex 中定义 Store 的语法非常近似,但是少了 Mutation 字段。

不仅如此,这种写法也和 Vue2 的 Options API(选项式 API)结构类似:statedata 对应、getterscomputed 对应、actionsmethods 对应。

这种写法的好处就是结构非常清晰,容易上手,特别是对刚从 Vue2 和 Vuex 转到 Pinia 的开发者!

安利 Setup Stores 语法

但 Setup Stores 语法更灵活、更函数:

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

  return { count, doubleCount, increment }
})

在这种语法中,refstate 对应、computedgetters 对应、functionactions 对应。

想必写过 Vue3 朋友就能一眼看出来这和 Vue3 新推出的 Composition API(组合式 API)非常类似!这样的话,在使用 Vue3 和 Pinia 的时候,就能统一语法了。

如果在 Vue3 的 Setup 语法外使用 Pinia 呢?

如果你准备在 Vue3 的 Setup 语法外引入 Pinia 的 Store,例如 useCounterStore。

直接 import { useCounterStore } from "@/store/modules/xxxxxx" 是不行的,你得像这样:

import store from "@/store"

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

  return { count, doubleCount, increment }
})

/** 在 setup 外使用 */
export function useCounterStoreHook({
  return useCounterStore(store)
}

然后引入 import { useCounterStoreHook } from "@/store/modules/xxxxxx" 即可!

参考资料

[1]

https://pinia.vuejs.org/: https://link.juejin.cn?target=https%3A%2F%2Fpinia.vuejs.org%2F

最后



如果你觉得这篇内容对你挺有启发,我想邀请你帮我个小忙:

  1. 点个「喜欢」或「在看」,让更多的人也能看到这篇内容

  2. 我组建了个氛围非常好的前端群,里面有很多前端小伙伴,欢迎加我微信「sherlocked_93」拉你加群,一起交流和学习

  3. 关注公众号「前端下午茶」,持续为你推送精选好文,也可以加我为好友,随时聊骚。



点个喜欢支持我吧,在看就更好了


浏览 17
点赞
评论
收藏
分享

手机扫一扫分享

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

手机扫一扫分享

举报