Skip to content

Pinia ​

Pinia 是拥有组合式 API 的 Vue 状态管理库,同时支持 Vue2 和 Vue3。

核心概念有:store、state、getter 和 action。

state、getter 和 action 分别相当于 store 的 data、computed 和 methods。

Store ​

使用 defineStore 函数定义 store,第一个参数为 store 名称,其名要唯一,store 可定义多个。

兼容 Vue2,传入一个带有 state、getters 和 actions 的对象。

js
// Option store
import { defineStore } from 'pinia'

export const userCounterStore = defineStore('counter', {
  // state是一个返回初始状态的函数,推荐箭头函数来进行完整的类型推理
  state: () => ({ count: 0 }),
  getters: {
    double: state => state.count * 2
  },
  actions: {
    increment() {
      this.count++
    }
  }
})

Vue3 推荐写法,传入一个函数,响应式数据作为函数返回值暴露出去。

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

使用 store ​

Vue2 可像 Vuex 一样使用辅助函数。

js
import { mapStores, mapState, mapActions } from 'pinia'  
import { userCounterStore } from '@/stores/counter'  
  
export default {  
  computed: {
    // 允许访问this.counterStore
    ...mapStores(userCounterStore),
    // 允许读取this.count和this.double
    ...mapState(useCounterStore, ['count', 'double'])
  },
  methods: {
    // 允许读取this.increment()
    ...mapActions(useCounterStore, ['increment'])  
  }
}

Vue3 中直接执行 store 的函数拿到返回值即可使用,其返回值是一个用 reactive 包装的对象,所以要注意解构引起的响应丢失问题,如果要解构 store,可先用 storeToRefs 函数来为每个响应式属性创建引用。

js
import { storeToRefs } from 'pinia'  
import { useCounterStore } from '@/stores/counter'  
  
const store = useCounterStore()  
store.count  
store.increment()  
  
// store 解构  
const { count } = storeToRefs(store)  
  
// action 可直接从 store 解构  
const { increment } = store

State ​

state 为一个返回初始状态的函数。

js
import { defineStore } from 'pinia'

const useStore = defineStore('storeId', {
  // 为了完整类型推理,推荐使用箭头函数
  state: () => {
    return {
      count: 0,
      items: []
    }
  }
})

访问 state ​

可直接通过 store 实例来对 state 进行读写。

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

const store = useCounterStore()  
store.count++

重置 state ​

选项式 API 使用 $reset() 方法将 state 重置为初始值,组合式 API 中需要自己定义重置的方法来手动重置状态。

js
const store = useStore()  
store.$reset()

修改 state ​

直接通过 store.count++ 直接修改 state 即可,但也支持使用 $patch 方法,该方法可以接收一个对象或函数。

js
store.$patch({  
  count: store.count + 1,  age: 120,  
})  
store.$patch(state => {  
  state.items.push({ name: 'shoes', quantity: 1 })  
  state.hasChanged = true
})

替换 state ​

可通过 $patch 来替换掉整个 state,也可通过修改 Pinia 实例的 state 来修改整个 state。

js
store.$patch({ count: 24 })  
pinia.state.value = {}

订阅 state ​

store 的 $subscribe() 方法可监听 state 的变化。

默认情况,组件卸载时,state subscription 会自动删除,如果想保留,可将 { detached: true } 作为第二个参数,以将 state subscription 从当前组件中分离。

js
store.$subscribe((mutation, state) => {  
  mutation.type // 'direct' | 'patch object' | 'patch function'
  // 和cartStore.$id一样
  mutation.storeId
  // 只有mutation.type==='patch object'的情况下才可用  
  mutation.payload // 传递给cartStore.$patch()的补丁对象。  
}, {detached: true})

Getter ​

选项式 API 中,state 会作为 getter 的第一个参数,如果要访问其他 getter,直接通过 this 来访问即可。

js
import { useOtherStore } from './other-store'  
  
export const useStore = defineStore('main', {  
  getters: {
    otherGetter(state) {
      const otherStore = useOtherStore()
      return state.localData + otherStore.data
    },
  }
})

Action ​

选项式 API 在 defineStore() 中用 actions 属性来定义即可,action 中的 this 可访问整个 store 实例。

订阅 action ​

可通过 store.$onAction() 来监听 action,传递给它的回调函数会在 action 本身之前执行。

after 表示在 Promise 解决之后,允许你在 action 解决后执行一个回调函数,同样地,onError 允许你在 action 抛出错误或 reject 时执行一个回调函数。

js
const unsubscribe = someStore.$onAction(({  
  name, // action名称  
  store, // store实例 
  after, // 在action返回或解决后的钩子  
  onError, // action抛出或拒绝的钩子  
}) => {  
  // 为这个特定的action调用提供一个共享变量  
  const startTime = Date.now()  // 这将在action成功并完全运行后触发  
    // 它等待着任何返回的promise
    after((result) => {})  
    // 如果action抛出或返回一个拒绝的promise,这将触发  
    onError((error) => {})
})  
  
// 手动删除监听器  
unsubscribe()

默认情况下,action 订阅器会在组件被卸载时自动删除,如果想在组件卸载后依旧保留它们,可将 true 作为第二个参数来传递,以便将其从当前组件中分离。

对比 Vuex+ ​

  • 弃用 mutation。
  • 没有 modules,Pinia 是扁平的结构。
  • 可构建多个 store。
  • 更好的 TS 支持。