vue3状态管理器pinia

223 阅读1分钟
前言

pinia或者叫vuex5,被作为与vue3组合式api配合使用的状态管理器。有更简洁的api,也兼容了vue2,同时也沿用了vuex的一些使用方式,对vue的老用户是非常友好的。

使用

1. 引用

import { createPinia } from 'pinia'
app.use(createPinia())

2. 初始化仓库

  • 支持注册多个仓库,第一个参数是该仓库的id
  • 修改state值去除了mutation,只保留了actions,支持同步和异步。
  • 可以继续使用getters

注册

import { defineStore } from 'pinia'

export const mainStore = defineStore('main', {
  state: () => {
    return { 
        userInfo: {
            name: '张三',
            age: 12,
            id: 000
        },
        count: 0 
    }
  },
  // 修改数据
  actions: {
    addCount() {
      this.count++
    },
  },
  getters: {
    getUserId(state) {
        return state.userInfo.id
    }
  }
})

使用

  • 可以通过拿到实例链式操作
  • 也可以通过storeToRefs解构出单独的属性
<template>
  <h1>{{ stateIns.userInfo }}</h1>
  <h1>{{ job }}</h1>
   <h1>{{ count }}</h1>
   <h1>{{ mainStoreIns.getUserId }} ++ {{getUserId}}</h1>
</template>

<script setup lang="ts">
import { mainStore } from '@/store/index.js'
import { storeToRefs } from 'pinia';
// 直接使用实例
const mainStoreIns = mainStore();

// 解构可解构属性,也可解构getter,类似ref
let { count, getUserId } = storeToRefs(mainStoreIns);
console.log(count.value)
</ script>

仓库之间数据使用

import { defineStore, storeToRefs } from 'pinia'
import { mainStore } from '@/store/index.js'

export const countStore = defineStore('count', {
  state: () => {num: 0 },
  getters: {
    getCount(state) {
        const mainStoreIns = mainStore();
        const {count} = storeToRefs(mainStoreIns)
        return state.num + count.value;
    }
  }
})

3. 修改state数据的方式

修改state值的5种方式

  • 1、stateIns.XX = YY
  • 2、stateIns.$patch({XXX: yyy}) 可以只修改单个值
  • 3、stateIns.$patch((state) => )
  • 4、stateIns.$state 全部覆盖
  • 5、action的方式stateIns.(action定义的方法)
<template>
  <h1>{{ stateIns.userInfo }}</h1>
  <h1>{{ count }}</h1>
  <h1>{{ mainStoreIns.getUserId }} ++ {{getUserId}}</h1>
  <button @click="changeState">change state</button>
</template>

<script setup lang="ts">
import { mainStore } from '@/store/index.js'
import { storeToRefs } from 'pinia';
// 直接使用实例
const mainStoreIns = mainStore();

// 解构可解构属性,也可解构getter,类似ref
let { count, getUserId } = storeToRefs(mainStoreIns);
const changeState = () => {
    // 1
    count.value++
    mainStoreIns.count++
    // 2 这里不会修改userInfo  里面age,id的值
    stateIns.$patch({userInfo: {
        name: '修改名字'
    }})
    // 3
    stateIns.$patch((state) => {
        state.count = 10
    })
    // 4 全部覆盖
    stateIns.$state = {
        userInfo: {
            id: 000
        },
        count: 1
    }
    // 5 调用action的方法
    stateIns.addCount();
}

</ script>