Pinia 是 Vue 的专属的最新状态管理库 ,是 Vuex 状态管理工具的替代品
提供更加简单的API(去掉了mutation)
提供符合组合式风格的API (和Vue3新语法统一)
去掉了modules的概念,每一个store都是一个独立的模块
配合TypeScript更加友好,提供可靠的类型推断
手动添加Pinia到Vue项目
在实际开发项目的时候,Pinia可以在项目创建时自动添加
初次学习,先从零开始:
- 使用 Vite 创建一个空的 Vue3项目(除了ESLint可以一路no)
npm init vite@latest
cd到项目
npm i
npm run dev
- 按照官方文档安装 pinia 到项目中 (Pinia | Pinia (vuejs.org))
yarn add pinia
# 或者使用 npm
npm install pinia
创建一个 pinia 实例 (根 store) 并将其传递给应用:
main.js 中
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
app.mount('#app')
运行项目
npm run dev
基本语法
src文件夹 下创建 store文件夹 ,可以建立多个仓库 xxx.js
import { defineStore } from 'pinia'
// 名字的规范一般是 use仓库名Store
export const 名字 = defineStore ('counter',()=>{
//声明数据 state - count
const count = ref(θ)
//声明操作数据的方法action(普通函数)
const addCount =() => count.value++
//声明基于数据派生的计算属性 getters(computed)
const double = computed (() => count.value * 2)
//可以进行组合式写法,声明数据 state -msg
const msg = ref('hello pinia')
return {
count,
msg,
addCount,
double
}
})
组件下
<script setup>
import { 名字 } from '@/store/文件名'
const counterStore = 名字()
// 不要对这个进行解构,否则会丢失响应式
console.log(counterStore)
</script>
<template>
<div>
{{ couterStore.count }}
<button @click = "counterStore.addCount"> + </button>
{{ counterStore.double }}
</div>
</template>
action 中的异步函数
直接写就行
import { defineStore } from 'pinia'
import{ ref } from 'vue'
import axios from 'axios'
// 名字的规范一般是 use仓库名Store
export const 名字 = defineStore ('counter',()=>{
//声明数据 state - count
const channelList = ref([])
//声明操作数据的方法
const getList = async () =>{
//支持异步
const { data:{ data }} = await axios.get('http://geek.itheima.net/v1_0/channels')
channelList.value = data.channels
}
return {
channelList,
getList
}
})
组件下
<script setup>
import { useChannelStore } from '@/store/文件名'
const ChannelStore = useChannelStore()
</script>
<template>
<div>
<button @click = "channelStore.getList">获取数据 </button>
<ul>
<li v-for="item in channerlStore.channelLIst" :"item.id">{{ item.name }}</li>
</ul>
</div>
</template>
storeToRefs工具函数
使用storeToRefs函数可以辅助保持数据(state + getter)的响应式解构
函数不需要响应式,就是调用,所以可以直接结构
storeToRefs
<script setup>
import { storeToRefs } from 'pina'
import { useCouterDStore} from '@/store/couter'
const couterStore = useCouterStore()
//此时,直接解构,不处理,数据会丢失响应式
const { count, msg } = storeToRefs(counterStore)
</script>
Pinia持久化插件
官方文档:https://prazdevs.github.io/pinia-plugin-persistedstate/zh/
- 安装插件 pinia-plugin-persistedstate
npm i pinia-plugin-persistedstate
- main.js文件下
// 导入持久化的插件
import persist from 'pinia-plugin-persistedstate'
const pinia = createPinia() // 创建Pinia实例
app.use(pinia.use(persist))
- 配置 store/counter.js
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
export const useCounterStore = defineStore('counter', () => {
...
return {
count,
doubleCount,
increment
}
}, {
persist: true // 开启当前模块的持久化
})