在 Vue 中使用 Pinia
Pinia 符合直觉的 Vue.js 状态管理库 (localStorage 超级进化版本)
一、 基本使用
想要在 vue 项目中使用主要有以下几个步骤
1. 安装 pinia
npm install pinia
2. 初始化(改写 main.js)
添加以下内容
// 导入
import { createPinia } from "pinia";
// 创建对象
const pinia = createPinia();
同时需要在默认 app 上添加 pinia
// 原本可能是这样
// createApp(App).mount("#app");
// 需要改写成下面的样子
const app = createApp(App);
app.mount("#app");
//添加这个
app.use(pinia);
3. 定义 store
- 在
vue
项目的src
目录下新建文件夹stores
- 在
stores
下新建一个xueStore.js
(文件名随意)
文件内容基本格式如下
import { defineStore } from "pinia";
import { ref } from "vue";
// 名字规范:use{yourStoreName}Store
export const useXueStore = defineStore("xue", () => {
// 这里写一些东西
const name = ref("雪中明月");
const level = ref(18);
const levelUp = () => {
level.value++;
};
// 注意要 return
return { name, level, levelUp };
});
4. 使用 store
现在万事具备,你可以在项目随意使用了
找到一个组件,例如 App.vue
<script setup>
import { useXueStore } from "./stores/xueStore";
const XueStore = useXueStore();
</script>
只需两步即可获取 store ,接下来试试使用里面的内容,补全 template
部分
<template>
name: {{ XueStore.name }} <br />
age: {{ XueStore.level }} <br />
<button @click="XueStore.levelUp">levelUp</button>
</template>
二、 数据持久化
不难发现,网页一刷新,上面的数据就会变成初始值,也许这不是我们大概不是我们想要的
我们需要添加一个 pinia
插件 pinia-plugin-persistedstate
1. 安装插件
npm install pinia-plugin-persistedstate
2. 初始化(改写 main.js)
添加以下内容
// 导入
import piniaPluginPersistedstate from "pinia-plugin-persistedstate";
同时需要在 pinia 上添加 插件
pinia.use(piniaPluginPersistedstate);
3. 开始使用
配置很简单,只需要添加一行
{
persist: true;
}
依旧是 xueStore.js
import { defineStore } from "pinia";
import { ref } from "vue";
export const useXueStore = defineStore(
"xue",
() => {
const name = ref("雪中明月");
const level = ref(18);
const levelUp = () => {
level.value++;
};
return { name, level, levelUp };
},
// 在这里添加一行,记得添加上面的**逗号**
{ persist: true }
);
注意:到此插件会按照默认配置进行本地化,
如果需要进一步的自定义
请查阅:插件配置 Doc
4. 对比 localstorage ?
优点 :全自动
三、 补充信息
1. 解构
和 reactive 一样,直接解构会使数据失去响应式
不同于 vue
的 toRef()
,对于 pinia
,
需要使用 storeToRefs()
import { storeToRefs } from "pinia";
2. Setup Store
1.2
中定义的方法官方称为 Setup Store
在 Setup Store
中:
ref()
就是state
属性computed()
就是getters
function()
就是actions
3. state getters actions 的解释
state
在大多数情况下,state 都是你的 store 的核心。人们通常会先定义能代表他们 APP 的 state。在 Pinia 中,state 被定义为一个返回初始状态的函数。这使得 Pinia 可以同时支持服务端和客户端。
state
里面写的是初始值
getters
Getter 完全等同于 store 的 state 的计算值。可以通过 defineStore() 中的 getters 属性来定义它们。推荐使用箭头函数
相当于 computed()
Action
Action 相当于组件中的 method。它们可以通过 defineStore() 中的 actions 属性来定义,并且它们也是定义业务逻辑的完美选择。
是普通的函数