Pinia 是 Vue 的专属的最新状态管理库 ,是 Vuex 状态管理工具的替代品
- 提供更加简单的API(去掉了 mutation)
- 提供符合组合式风格的API(和 Vue3 新语法统一)
- 去掉了 modules 的概念,每一个 store 都是一个独立的模块
- 搭配 TypeScript 一起使用提供可靠的类型推断
添加Pinia到Vue项目
- 使用 create-vue 创建空的新项目
npm init vue@latest
- 按照官方文档安装 pinia 到项目
安装
- 安装
yarn add pinia / npm install pinia
- 配置/main.js
import './assets/main.css'
import { createApp } from 'vue'
import App from './App.vue'
// 1. 导入createPinia
import { createPinia } from 'pinia'
// 2. 执行方法 得到实例
const pinia = createPinia()
// 3. 把pinia实例加入到app应用中
createApp(App).use(pinia).mount('#app')
- 使用
定义 Store:
// stores/counter.js
// 导入一个方法 defineStore
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {
// 定义数据(state)
const count = ref(0)
// 定义修改数据的方法(action 同步+异步)
const increment = () => {
count.value++
}
// 以对象的方式 return 供组件使用
return {
count,
increment
}
})
组件使用:
<script setup>
// 1. 导入 use 打头的方法
import { useCounterStore } from '@/stores/counter'
// 2. 执行方法得到实例对象
const counterStore = useCounterStore()
</script>
<template>
<button @click="counterStore.increment()">{{ counterStore.count }}</button>
</template>
<style scoped>
</style>
Getters实现
Pinia中的 getters 直接使用 computed 函数 进行模拟。
Getter 完全等同于 store 的 state 的计算值。
- getter定义// stores/counter.js
const doubleCount = computed(() => count.value)
- 组件使用
<template>
<button @click="counterStore.increment">{{ counterStore.count }}</button>
{{ counterStore.doubleCount }}
</template>
Action
Action 相当于组件中的 method。、
action中实现异步和组件中定义数据和方法的风格完全一致
// stores/counter.js
const API_URL = 'http://geek.itheima.net/v1_0/channels'
- 定义异步action:
const list = ref()
const getList = async () => {
const res = await axios.get(API_URL)
list.value = res.data.data.channels
}
- 组件使用:
onMounted(()=>{
counterStore.getList()
})
<ul>
<li v-for="item in counterStore.list" :key="item.id">{{ item.name }}</li>
</ul>
storeToRefs
使用 storeToRefs函数 可以辅助保持数据 (state+getter) 的响应式解构// stores/counter.js
// 直接解构赋值(响应式丢失)
// const { count, doubleCount } = counterStore
// 方法包裹(保持数据响应式)
const { count, doubleCount } = storeToRefs(counterStore)
// 方法直接从原来的 counterStore 中解构赋值
const { increment } = counterStore
storeToRefs 和 toRefs 都可以将对象转换为具有 .value 的 ref 对象集合。
区别:
-
storeToRefs 是针对 pinia 的 store 对象
-
toRefs 是 Vue 3 中的通用函数,用于处理任意的响应式对象