几分钟掌握Pinia 的基本使用

什么是 Pinia

Pina开始于大概2019,是一个状态管理的库,用于跨组件、页面进行状态共享(这和Vuex、Redux一样),用起来像组合式API(Composition API)

为什么Vue官方推荐使用Pinia 而不在推荐使用 Vuex,Pinia优点如下:

1.Pinia 已经实现了Vue5 的大部分内容
2.与Vuex相比,Pinia提供了一个更简单的API,具有更少的仪式,提供了Composition-API风格的API
3.Pinia与TypeScript一起使用时具有可靠的类型推断支持
4.Pinia不在有命名空间的概念,不在需要记住他们的复杂关系
5.不在有modules的嵌套结构

如何安装Pinia
  // 使用 yarn   或者 使用 npm
  yarn add pinia;
  npm i pinia;

使用 Pinia

在 src 目录下新建 store文件夹,再在store中新建 index.ts 文件

 不在有modules的嵌套结构
// inde.ts

import type { App } from 'vue'
import { createPinia } from 'pinia'
import useUserStore from './modules/users'
// 创建store
const store = createPinia()
// 用于在main.js中注册
export function registerStore( app: App ) {
 app.use( store )
}
// 导出可在vue页面中进行使用
export { useUserStore }
// 全部整个store
export default store;
在main.ts中进行引入
  // 引入 Pinia
  import { registerStore } from '/@/store'
  // 注册
  registerStore( app )

在 store 文件夹下 创建 type.ts 文件 用于存放各个模块的类型
 export type TypeInfo ={
    count:number
    data:{
      name:string
      sex:string
    }
  }
进行分模块

// 在store下 新建 modules 文件夹,存放不同的模块处理

// 新建useUserStore.ts 文件
// Pinia 中没有了 没有了 mutations
// 分模块 useUserStore
import { defineStore } from 'pinia'
// 用于存放类型
import { TypeInfo } from "@/store/type"
// defineStore 调用后返回一个函数,调用该函数获得 Store 实体
export const useStore = defineStore({
  // id: 必须,在所有 Store 中唯一
  id: 'useStore',
  // state: 返回对象的函数
  state: () :TypeInfo=> ({
    count: 1,
    data: {
      name: 'Jerry',
      sex: '男'
    }
  }),
  // getter 第一个参数是 state,是当前的状态,也可以使用 this 获取状态
  // getter 中也可以访问其他的 getter,或者是其他的 Store
  getters: {
    // 通过 state 获取状态
    doubleCount: (state) => state.count * 2,
    // 通过 this 获取状态(注意this指向)
    tripleCount() {
      return this.count * 3
    }
  },
  actions: {
    updateData (newData, count) {
      // 使用 this 直接修改
      this.data = { ...newData }
      this.count = count
      
      // 使用 $patch 修改多个值
      this.$patch({
        data: { ...newData },
        count
      })
    }
  }
})
在页面中进行使用 Pinia
// 页面中进行使用
<template>
  // 获取 store 的 state
  <p>姓名:{{store.data.name+‘’-----‘+store.data.sex}}</p>
  // 调用 actions 方法 / 修改 store
  <button @click='update'>修改用户信息</button>
</template>
<script setup>
  // 
  import { useStore } from '@store/store.js'
  const store = useStore()
  // $reset 重置状态获取初始值
  store.$reset()
    // $state 可以让你通过将 store 的属性设置为新对象来替换 store 的整个 state
  store.$state = {
    name: 'huai',
    sex: '男'
  }

  function update () {
    // 通过 actions 定义的方法修改 state
    store.updateData({ name: '淮丫丫', sex: '女' })
    
    // 通过 store 直接修改
    store.data = { name: '淮丫丫', sex: '女' }
    
    // 同时改变多个状态
    store.$patch((state) => {
      state.data = { name: '淮丫丫', sex: '女' }
      state.count = 2
    })
  }
</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容