Pinia的基本使用

引入Pinia

//下载依赖
npm install pinia

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

定义一个store

通过defineStore 来定义 store,它需要一个唯一的名称,作为第一个参数传入:

//@/store/user.js

import { defineStore } from 'pinia'

export const useUserStore = defineStore ({
  id:'user',//id必填,且需要唯一
  // 定义state,用来存储状态的
  state:()=>{
    return {
    count:0,
    arr:[1,2,3]
    }
  },
  // 定义actions,类似于methods,用来修改state,做一些业务逻辑
  action:{
    //接收一个参数num,参数的类型是number类型
    addCount(num:number){
      //通过this获取state中的数据,就像vue2的optionsApi一样
        this.count += num
    }
  },
  // 定义getters,类似于computed,具有缓存g功能
  getters:{
    //依赖state
    doubleCount(state){
        return  state.count*2 
    },
    //依赖其他的getters, :number 是指定返回值类型为number类型
    otherCount():number{
        return this.doubleCount + 1
    }
  }

})

使用store

注意,将state结构之后,就不是响应式的了,如果想要解构,则需要使用 storeToRefs 函数包裹。
原因很简单,store 其实就是一个 reactive 对象,当我们解构的时候,就不是响应式数据了,就像 vue3 中一样,需要使用 toRefs 函数。

import { useUserStore  } from '@/store/user.js'

<template>
  {{count}}
  {{arr}}
</template>

<script setup lang='ts'>
  // 拿到store
  const userStore= useUserStore ()
  // 这样就不是响应式的了,当我们修改count的值的时候,页面不会响应式变化
  const { count,arr } = storeToRefs(userStore)//// 正确的做法
  console.log(userStore.count) // 

  //修改state
  //方式一 直接修改
  userStore.count +=1
  //方式二 如果修改多个数据,可以使用$patch批量修改
  userStore.$patch({
    count: userStore.count+1,
    arr:[...userStore.arr,4]
  })
  //方式三,$patch一个函数
  userStore.$patch(state=>{
    state.count++
    state.arr.push(4)  
  })
  //方式四,调用actions
  userStore.addCount(10)
  //方式五,替换整个state
  userStore.$state={
    count:2,
    arr:[1,2,3,4]
  }
  //方式六,重置state
  userStore.$reset()

  //获取getters
  console.log(userStore.doubleCount)
  console.log(userStore.otherCount)
</script>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容