Pinia 是 Vue 的存储库,它允许您跨组件/页面共享状态。 如果您熟悉 Composition API,您可能会认为您已经可以通过一个简单的 export const state = reactive({}). 这对于单页应用程序来说是正确的,但如果它是服务器端呈现的,会使您的应用程序暴露于安全漏洞。
Pinia的好处?
- dev-tools 支持
跟踪动作、突变的时间线
Store 出现在使用它们的组件中
time travel 和 更容易的调试
- 热模块更换
在不重新加载页面的情况下修改您的 Store
在开发时保持任何现有状态
- 插件:使用插件扩展 Pinia 功能
- 为 JS 用户提供适当的 TypeScript 支持或 autocompletion
- 服务器端渲染支持
与 Vuex 相比,Pinia 提供了一个更简单的 API,具有更少的规范,提供了 Composition-API 风格的 API,最重要的是,在与 TypeScript 一起使用时具有可靠的类型推断支持。
下面让我们在Vue3项目中使用Pinia:
第一步下载Pinia:
npm install pinia
第二步在 main.js 中配置pinia 全局引入:
下面创建pinia 数据:
stores/counter.js
// stores/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => {
return { count: 0 }
},
// 也可以定义为
// state: () => ({ count: 0 })
actions: {
// 加数量方法
increment() {
this.count++
},
},
})
在组件中使用:
<template>
<!-- 渲染 -->
{{ counter.count }}
<!-- 触发方法数量加一 -->
<el-button @click="add">加一</el-button>
</template>
<script setup>
import { useCounterStore } from '@/stores/counter'
// 获取pinia中的数据
const counter = useCounterStore()
// 加数量方法
function add() {
counter.$patch({ count: counter.count + 1 })
// 或使用 action 代替 触发action 方法
// counter.increment()
}