什么是pinia
pinia本质上依然是一个状态管理的库,用于跨组件,页面进行状态共享
pinia与vuex的区别
比如mutation不再存在 更友好的TS的支持 不再有modules的嵌套结构 也不再有命名的空间的概念,不需要记住他们的复杂描述
store
一个store是一个实体,会持有绑定到你组件树的状态和业务逻辑,也就是保存了全局的状态 它有三个核心概念 state,getters,actions等同于组件的data,computed,methods 一旦store被实例化,你就可以直接在store上访问state,getters和actions中定义的任何属性
如何使用
//安装
yarn add pinia
npm install pinia
//stores文件下的index.js文件
import {createPinia} from 'pinia'
const pinia=createPinia()
export default pinia
//counter.js
import {defineStore} from 'pinia'
const useCounter= defineStore("counter",{
state:()=>({
count:00
});
getters:{
doubleCounter:(state)=>state.counter*2
},
actions:{
increment(){
this.count++
}
}
})
export default useCounter
//在Home.vue中
<template>
<h2>count:{{counterStore.count}}</h2>
</template>
<script setup>
import useCounter from '@/stores/counter';
const counterStore=useCounter()
const {count}=storeToRefs(userStore)
function changeState(){
counterStore.incrementNum(10)
}
<script>
//main.js下
import pinia from './store'
create(App).use(pinia).mount('#app')
//重置State:
const counterStore=useCounter()
counterStore.$reset()
//可用$patch方法调用
counterStore.$patch({counter:100,name:xcc})
//替换State
counterStore.$state={
counter:1,
name:"xxx"
}
认识和定义Getters
相当于Store的计算属性 可以用defineStore()中的getters属性定义 getters中可以定义接受一个state()作为参数的函数
//访问当前store的Getters:
const counterStore=useCounter()
console.log(counterStore.doubleCounter)
//Getters中访问自己的其它Getters,可以通过this来访问到当前store实例的所有属性
doublePlusOne:function(state){
return this.doubleCounter+1
}
//访问其它store的Getters
message:function(state){
const userStore=useUser()
return this.fullname+":"+userStore.nickname
}
//Getters也可以返回一个函数,这样就可以接受参数
//在home.vue中 <h2> Use:{{getUseById(111)}}<h2>
getters:{
getUseById(state){
return userId=>{
return state.users.find(item=>item.id===suerId)
}
}
}
认识和定义Action
支持异步操作,可在函数中使用await
//在home.js
import {defineStore} from 'pinia'
const useHome=defineStore("home",{
state:()=>({
banners:[],
recommends:[]
}),
action:{
async fetchHomeMultidata(){
const res=await fetch("http://123.207.32.32:8000/home/multidata")
const data=await res.json()
this.banners=data.data.banner.list
this.recommends=data.data.recommend.list
}
}
})