Pinia的写法探索

在最新的 Vue 官方文档中,核心库的地址已经指向了Pinia,这表明已经把 Pinia 当做 Vue3.x 的官方状态管理库了。下面来探索下 Pinia 的使用方式。

基础

在 Pinia 的首页文档上介绍了最基础的使用方式:

// stores/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => {
    return { count: 0 }
  },
  // could also be defined as
  // state: () => ({ count: 0 })
  actions: {
    increment() {
      this.count++
    },
  },
})

注意上图的代码,里面用了this.count++ 在我第一次看到的时候,就觉得不舒服,因为整个项目已经是 Composition 的写法了,已经不再使用this了,不明白官方的推荐写法为什么是这样的。

所以我去提了个 issue:use state instead of this in actions

作者回复了:

There are two reasons actions do not take any parameters by default:

- Allow the user to define any parameters as they want
- Type support: passing the state wouldn't be enough in actions, we would need to pass the store but then actions wouldn't be automatically typed because of a limitation in TS

This is not stated in docs because it's an implementation detail and would confuse most users.

解决方案

看完之后我感觉并没有说清楚,后来自己又在文档首页发现了下面这样的写法:

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

  return { count, increment }
})

感觉还不错,使用最新的 Vue.js devtools 调试,发现这种也会有一个 state ,调用方法的时候也会有 pinia 的 action 记录产生,调试没问题

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值