Pinia学习

147 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 9 天,点击查看活动详情

Pinia

Pinia是vue的专属状态管理库,允许跨组价或页面共享状态。

适用于中小型项目。

创建vue3项目安装pinia

安装pinia

npm install pinia

在main.js中引入pinia

import {createPinia} from 'pinia'
const pinia = createPinia();
​
app.use(pinia)
  • 在pinia中有state(类似于data)和getter(类似于computed)和action(类似于methods)
  • 将共享的数据存放到store中
Option Store
import { defineStore } from "pinia";
​
//option store
export const useAgeStore = defineStore('main',{
    state:() =>{  //一个函数
        return {
            age:30,
        }
    },
    getters:{  //对象
        gettersAge(state) { //在getters中必须接收对象才能进行处理
            return state.age + 5;
        }
    },
    actions:{ //将方法定义在actions中
        addAge(){
         this.age++; //this是整个store仓库
        }
    }
})
Setup Store
export const useCounterStore = defineStore('main',()=>{
    const counter = ref(30);
    const gettersCounter = computed(()=>{
        return counter.value + 5;
    }) 
    function addCounter(){
        counter.value++;
    }
    return {
        counter,
        gettersCounter,
        addCounter
    }
})
在页面中使用
{{ ageStore.age }}
    {{ ageStore.gettersAge }}
    <button @click="ageStore.addAge">修改age值</button>

使用es6的解构将store进行解构是无法生效的,因为他破坏了响应式

const {age,gettersAge} = storeToRefs(ageStore);
const {age,gettersAge} = storeToRefs(ageStore);

storeToRefs可以将state和getters进行解构,但是action不能进行解构。

State

修改state中的状态,

方式一

function change(){
ageStore.age++;
}

方式二:批量修改

ageStore.$patch({
age:40,
name:'张三',
arr:[...ageStore.arr,5]
})

方式三:使用函数进行批量修改

ageStore.$patch((state)=>{
    state.age = 40;
    state.name = '张三丰';
    state.arr.push(9);
})

方式四:对于逻辑比较复杂的函数,将函数封装到action中

getters

在getters中使用this就不能使用箭头函数

访问其他getters

gettersPlusAge(state){
            return this.gettersAge + state.name;
        }

有参的getters

gettersPlusAge(state){
            return (a) =>{
                state.age += a;
            }
        }

action

在actiosn中的this指的是store仓库,使用this就不能使用箭头函数,actions是可以处理同步和异步的,一定要使用普通函数

  • 在vuex使用mutations处理同步,actions处理异步