Pinia学习记录

Pinia官方文档

1. Pinia 特点简介:

  1. Pinia 适用于 Vue 2 和 Vue 3
  2. 使用Composition API设计适用于 Vue 的 Store,类似于vue的vuex状态管理库;
    也类似于React 的Recoil,但没有那么多的概念和 API,主体非常精简,极易上手(Recoil 是 Facebook 官方出品的用于 React 状态管理库,使用 React Hooks 管理状态)
  3. 服务器端渲染支持

2. 基础使用:

创建store:

// 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++
    }
  }
})

使用示例:

import { useCounterStore } from '@/stores/counter'

export default {
  setup() {
    const counter = useCounterStore()

    counter.count++
    // with autocompletion ✨
    counter.$patch({ count: counter.count + 1 })
    // or using an action instead
    coutner.increment();
  },
}

Pania 也支持类似Vuex 的一组地图助手。您以相同的方式定义商店,但随后使用mapStores(), mapState(), 或mapActions():

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

const useUserStore = defineStore('user', {
  // ...
})

export default {
  computed: {
    // other computed properties
    // ...
    // gives access to this.counterStore and this.userStore
    ...mapStores(useCounterStore, useUserStore)
    // gives read access to this.count and this.double
    ...mapState(useCounterStore, ['count', 'double']),
  },
  methods: {
    // gives access to this.increment()
    ...mapActions(useCounterStore, ['increment']),
  },
}

版权声明:本文为var_deng原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。