问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

Vue3 Pinia详解使用指南

创作时间:
作者:
@小白创作中心

Vue3 Pinia详解使用指南

引用
CSDN
1.
https://blog.csdn.net/qq_36410795/article/details/137638813

Pinia是Vue3的专属状态管理库,作为Vuex的替代品,提供了更简单、更符合组合式API风格的状态管理方案。本文将从Pinia的基本概念、功能作用,到具体的安装配置、基础使用、getters实现、action异步处理、storeToRefs工具函数的使用,以及调试方法等各个方面进行详细讲解。

1. Pinia 是什么

  1. Pinia是Vue的专属最新状态管理库
  2. 是Vuex状态管理工具的替代品,为Vue项目提供共享状态管理工具
  3. 支持Vue2和Vue3,主要是为Vue3提供状态管理,支持TypeScript
  4. Pinia可以创建多个全局仓库,不用像Vuex那样一个仓库嵌套模块,结构复杂。管理数据简单,提供数据和修改数据的逻辑即可,不像Vuex需要记忆太多的API

2. Pinia 功能作用

  1. 提供更加简单的API(去掉了mutation)
  2. 提供符合组合式风格的API(和Vue3新语法统一)
  3. 去掉了modules的概念,每一个store都是一个独立的模块
  4. 配合TypeScript更加友好,提供可靠的类型推断

3. 手动添加Pinia到Vue项目

Pinia可以在项目创建时自动添加,现在我们初次学习,从零开始:

使用 Vite 创建一个空的TS + Vue3项目

npm create vite@latest vue-pinia-ts -- --template vue-ts

按照官方文档安装pinia到项目中:

cnpm i pinia

4. Pinia基础使用

  1. 在src中定义一个stores文件夹,新建counter.ts文件
  2. counter.ts组件使用store
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useCounterStore = defineStore('counter', () => {
    // 数据(state)
    const count = ref(0)
    // 修改数据的方法(action)
    const increment = () => {
        count.value++
    }
    // 已对象的形式返回
    return {
        count,
        increment
    }
})
  1. main.js中引入pinia
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'

const pinia = createPinia();
createApp(App).use(pinia).mount('#app')
  1. App.vue页面中使用
<script setup>
// 1. 导入 useCounterStore 方法
import { useCounterStore } from './stores/counter'
// 2. 执行方法得到counterStore对象
const counterStore = useCounterStore();
</script>
<template>
  <div>{{counterStore.count}}</div>
</template>

5. getters实现

  1. Pinia中的getters直接使用computed函数进行模拟,组件中需要使用需要把getters return出去
const doubleCount = computed(() => count.value * 2)

6. action异步实现

方式:异步action函数的写法和组件中获取异步数据的写法完全一致

const getList = async ()=>{
    const res = await axios.request<接口数据类型>({})
}

7. storeToRefs工具函数

使用storeToRefs函数可以辅助保持数据(state + getter)的响应式解构

<script setup>
import { storeToRefs } from 'pinia'
import { useCounterStore } from './stores/counter'

// 使用storeToRefs保持数据响应式
const { count } = storeToRefs(useCounterStore());

function add() {
  counterStore.increment()
}
</script>
<template>
    <p class="mt-4">
      number:<strong class="text-green-500"> {{ count }} </strong>
    </p>
    <button class="btn" @click="add">
      Add
    </button>
</template>

8. Pinia的调试

Vue官方的dev-tools调试工具对Pinia直接支持,可以直接进行调试

9. 总结

  1. 通过

const useCounterStore = defineStore('counter', () => {})

创建数据仓库

  1. Vuex中的state在pinia中可以引用ref和reactive创建响应式数据
  2. Vuex中的getters在pinia中可以引用computed创建计算属性
  3. Vuex中的mutations和actions在pinia中就是普通函数,同步异步都可以
© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号