介绍

image.png
image.png

pinia只有state、getters、actions三个 actions 同步异步都支持,不需要像vuex封装mutations

pinia VS vuex

image.png

安装&创建

  1. npm init vite@latest
  2. npm install pinia
  3. main.js创建引用 ```javascript import { createPinia } from ‘pinia’ const pinia = createPinia();

const app = createApp(App) app.use(pinia)

  1. 4. 创建文件导出store
  2. ```javascript
  3. import { defineStore } from 'pinia'
  4. export const useMainStore = defineStore('main', {
  5. state() {return {}},
  6. getters: {},
  7. actions: {}
  8. })

基本使用

state

store/index.ts

  1. state() {
  2. return {
  3. count: 100,
  4. arr: [1, 2, 3]
  5. }
  6. },

xx.vue 展示数据

<p>{{mainStore.count}}</p>
<p>{{count}}</p>

import {storeToRefs} from 'pinia'
import {useMainStore} from '../store'

const mainStore = useMainStore();
let {count} = storeToRefs(mainStore)

acionts

store/index.ts 修改数据、异步操作数据

actions: {
  changeState(num: number) {
    // 方式一
    this.count += num;
    this.arr.push(4);

    // 方式二、三
    this.$patch({})
    this.$patch(state => { })
  },
  //异步调用接口
  async getProducts(){
    const ret = await getProducts()
    //赋值给state
    this.all = ret
  }
}

xx.vue

import {useMainStore} from '../store'
const mainStore = useMainStore();

const handleChangeState = ()=>{
  //方式一: 直接修改
  mainStore.count+1;
  mainStore.arr.push(4)

  //方式二:通过$patch批量修改
  mainStore.$patch({
    count:mainStore.count+1,
    arr:[...mainStore.arr,4]
  })

  // 方式三:通过$patch更简介方式
  mainStore.$patch(state=>{
    state.count++
    state.arr.push(4)
  })

  //方式四:通过acionts
  mainStore.changeState(5)
}

getters

store/index.ts

getters: {
  doubleCount(state) {
    return state.count * 2;
  }
  //如果ts使用this时要指定返回值类型
  doubleCount(): number {
    return this.count * 2;
  }
},

使用与state相同

跨模块使用

store/a.ts

//userAStore

actions:{
    add(num){
      this.count += num;
  }
}

store/b.ts

//userBStore
import {userAStore} from './b.ts'

actions:{
    addForA(){
      const aStore = userAStore()
    aStore.add(5)
  }
}

devtooles

image.png