首先引用官方文档,介绍Pinia是什么?
Pinia 是 Vue 的专属状态管理库,它允许你跨组件或页面共享状态。
那么如何使用Pinia?
我是使用的vue3,首先需要在main.js中导入pinia相应的包
import { createPinia } from 'pinia'
const pinia = createPinia()
这里如果按照我的理解的话,那就相当于是去创建一个 pinia 的实例对象
ps:在学习阶段如果忘记了导入pinia,没有在main.js文件中创建实例对象,直接在stores文件夹中去创建‘store.js’的话,会报如下的错误:
以上的步骤完成之后,pinia的学习就正式开始了
Store是什么?
这里引用官方文档的解释:
Store 是一个保存状态和业务逻辑的实体,它并不与你的组件树绑定。换句话说,它承载着全局状态。它有点像一个永远存在的组件,每个组件都可以读取和写入它。它有三个概念,state、getters和 actions,我们可以假设这些概念相当于组件中的data、computeds和 methods。
这里第一天我们练习pinia,构建store仓库
都是在stores这个文件下执行的
/stores/counter.js
import { defineStore } from "pinia";
export const useCounterStore = defineStore('counter',{
state:()=>{
return {
count:0
}
},
getters:{},
actions:{
increment(){
this.count++
}
}
})
因为Store是用 defineStore() 定义的,所以首先都是需要导入pinia实例对象的fineStore方法
import { defineStore } from 'pinia'
接着调用defineStore(),方法内需要传入两个参数,第一个参数是独一无二的仓库名,例如这里我们需要一个计数模块,就用counter来作为仓库名称,在这个counter仓库里我们去写一些数据和方法
/components/PageCounter.vue
<script setup>
import {useCounterStore} from '@/stores/counter.js'
const counter = useCounterStore()
counter.count++
counter.$patch({ count: counter.count + 1 })
const reset =()=>{
counter.$reset()
console.log(counter.count);
}
</script>
<template>
<div>
<div>Current Count: {{ counter.count }}</div>
</div>
<button @click="reset">重置</button>
</template>
运行结果:
这里按照我们在组件中写的样式,打印出 Current Count: 2
首先我们counter这个仓库内存在的数据对象是count,我们给的初始值是0;
首先我们要知道怎么去操作counter仓库里的数据,在counter.js中我们export导出了一个方法:useCounterStore() ,然后在组件模块中我们要导入这个方法,然后调用这个useCounterStore()方法并定义一个 counter 对象来接收 useCounterStore() 的返回值。
通过counte这个对象就可以对counter仓库里的数据做修改
.$patch()方法是对counter的数据做批量修改,这里只有count一个数据对象所以不太能直观的感受.$patch()的效果。这里先了解一下如何使用即可,后续学习完会进行补充。
这里我们pinia存储的count数据是2,然后我们通过重置按钮
count 被重置为0 ,但这里注意我们刷新完页面,count的值会返回到原来的值
这表明在页面操作修改数据之后,并没有再存储进pinia中。
所以下一步我们要进行pinia的持久化学习
首先我们要安装插件 pinia-plugin-persistedstate
pnpm add pinia-plugin-persistedstate -D
然后在main.js中使用
import persist from 'pinia-plugin-persistedstate'
app.use(createPinia().use(persist))
接着我们要配置counter仓库
import { defineStore } from "pinia";
export const useCounterStore = defineStore('counter',{
state:()=>{
return {
count:0
}
},
persist:true,
getters:{},
actions:{
increment(){
this.count++
}
}
})
关键的就是在state对象后加一个 persist:true ,表示开启持久化
这里页面稍微改了一下
/components/PageCounter.vue
<script setup>
import {useCounterStore} from '@/stores/counter.js'
const counter = useCounterStore()
// counter.count++
// counter.$patch({ count: counter.count + 1 })
const reset =()=>{
counter.$reset()
console.log(counter.count);
}
const add=(val)=>{
counter.count+=val
}
</script>
<template>
<div>
<div>Current Count: {{ counter.count }}</div>
</div>
<button @click="reset">重置</button>
<button @click="add(10)">+10</button>
</template>
运行结果:我们先重置为0
然后点击+10按钮
刷新之后数据不会返回原值,代表持久化成功
这里多点几次数据持续更新并存储在pinia仓库中。
至此pinia第一天的学习就先这样,可能有些地方的理解比较片面,后面继续深入学习会稍加修正的。