1.pinia介绍
pinia 是 Vue 的存储库,它允许您跨组件/页面共享状态。就是和vuex一样的实现数据共享。Pinia 目前也已经是 vue 官方正式的状态库。适用于 vue2 和 vue3。可以简单的理解成 Pinia。也就是说,Vue3 项目,建议使用Pinia。
Pinia 的优点
- pinia 符合直觉,易于学习。
- pinia 是轻量级状态管理工具,大小只有1KB.
- pinia 模块化设计,方便拆分。
- pinia 没有 mutations,直接在 actions 中操作 state,通过 this.xxx 访问响应的状态,尽管可 以直接操作 state,但是还是推荐在 actions 中操作,保证状态不被意外的改变。
- store 的 action 被调度为常规的函数调用,而不是使用 dispatch 方法或者是 MapAction 辅助函数,这是在 Vuex 中很常见的。
- 支持多个 store。
- 支持 Vue devtools、SSR、webpack 代码拆分。
2.pinia基本使用
- 首先先安装依赖
npm install pinia
- 在main.js中引入pinia并创建容器挂载到根实例上
//引入stores暴露出的pinia的实例
import pinia from './stores'
createApp(App).use(pinia).mount('#app')
- 创建stores文件夹和index.js文件(这个文件以后基本不用管了)
import { createPinia } from "pinia";
const pinia = createPinia()
export default pinia
- 在stores文件夹下创建counter.js文件。这个文件就是存有关counter相关的数据。(类似vuex的模块化)
defineStore 是需要传参数的
- 第一个参数是id,就是一个唯一的值,简单点说就可以理解成是一个命名空间.
- 第二个参数就是一个对象,里面有三个模块需要处理,第一个是 state,第二个是 getters,第三个是 actions。
//定义关于counter的store
import {defineStore} from 'pinia'
/*defineStore 是需要传参数的,其中第一个参数是id,就是一个唯一的值,
简单点说就可以理解成是一个命名空间.
第二个参数就是一个对象,里面有三个模块需要处理,第一个是 state,
第二个是 getters,第三个是 actions。
*/
const useCounter = defineStore("counter",{
state:() => ({
count:66,
}),
getters: {
},
actions: {
}
})
//暴露这个useCounter模块
export default useCounter
注意:返回的函数统一使用useXXX作为命名方案,这是约定的规矩。例如上面的useCounter
- 然后在组件中使用:
<template>
<!-- 在页面中直接使用就可以了 不用 .state-->
<div>展示pinia的counter的count值:{{counterStore.count}}</div>
</template>
<script setup>
// 首先需要引入一下我们刚刚创建的store
import useCounter from '../stores/counter'
// 因为是个方法,所以我们得调用一下
const counterStore = useCounter()
</script>
注意:在模板使用 ,不用和vuex一样还要.state,直接点state里面的K