pinia(Store)

127 阅读1分钟

Pinia 起始于 2019 年 11 月左右的一次实验,其目的是设计一个拥有组合式 API 的 Vue 状态管理库。

pinia简单理解就是vuex5,只不过换了个名字而已。

Store 是用 defineStore() 定义的

defineStore()的参数一:独一无二的id

defineStore()的参数二可接收两类值:Setup函数或Option对象

Option Store

  •   state --- (data) --- 数据
  •   getters --- (computed) --- 计算属性
  •   actions --- (methods) --- 方法
export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    double: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})

Setup Store

  • ref() --- state --- 属性
  • computed() --- getters --- 计算属性
  • function() --- actions --- 方法
export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  function increment() {
    count.value++
  }

  return { count, increment }
})

使用Store

storeToRefs()创建一个引用对象,包含 store 的所有 state、 getter 和 plugin 添加的 state 属性。 类似于 toRefs(),但专门为 Pinia store 设计, 所以 method 和非响应式属性会被完全忽略。

为了从 store 中提取属性时保持其响应性,你需要使用 storeToRefs()

如果只使用 store 的状态而不调用任何 action 时,storeToRefs()它会非常有用。

可以直接从 store 中解构 action,因为它们也被绑定到 store 上:

<script setup>
import { storeToRefs } from 'pinia'
const store = useCounterStore()
// `name` 和 `doubleCount` 是响应式的 ref
// 同时通过插件添加的属性也会被提取为 ref
// 并且会跳过所有的 action 或非响应式 (不是 ref 或 reactive) 的属性
const { name, doubleCount } = storeToRefs(store)
// 作为 action 的 increment 可以直接解构
const { increment } = store
</script>