什么是Pinia
Pinia是一个Vue的专属的最新状态管理库,是vuex状态管理工具的替代品
Pinia的优势
1.提供更加简单的API(去掉了 mutation)
 2.提供符合组合式风格的API(和vue3语法统一)
 3.去掉了modules的概念,每一个store都是一个独立的模块
 4.搭配TypeScript一起使用提供可靠的类型推断
添加Pinia到vue项目
1.使用create-vue创建空的项目
npm init vue@latest
 

2.安装pinia到项目
npm install pinia
 

Pinia的基础使用
1.使用Pinia实现计数器案例
 步骤:1️⃣定义store
 2️⃣组件中使用store 
// stores/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {
//定义数据(state)
  const count = ref(0)
 //定义修改数据的方法(action同步+异步)
  function increment() {
    count.value++
  }
//以对象的方式return共组件使用
  return { count, increment }
})
 
//组件中使用
<script setup>
  //1.导入use打头的方法
  import {useCounterStore} from '@/stores/counter'
  //2.执行方法得到store实例对象
  const counterStore = useCounterStore()
</script>
<template>
 <button @click='counterStore.increment'>{{counterStore.count}}</button>
</template>
 
Pinia—getters和异步action
getters实现
Pinia中的getters直接使用computed函数进行模拟
 
 
action实现
action中实现异步和组件中定义数据和方法的风格完全一致
 
 
Pinia—storeToRefs
storeToRefs
 使用storeToRefs函数可以辅助保持数据(state和getter)的响应式解构
 
 
总结
1️⃣Pinia是用来做什么的?
 集中状态管理工具,新一代的vuex
2️⃣Pinia中还需要mutation吗?
 不需要,action既支持同步也支持异步
3️⃣Pinia如何实现getter?
 computed计算性函数
4️⃣Pinia产生的Store如何解构赋值数据保持响应式?
 storeToRefs



















