安装pinia
npm i pinia
在mian.js文件注册pinia
import "./assets/main.css";
import { createApp } from "vue";
import App from "./App.vue";
import { createPinia } from "pinia";
const app = createApp(App);
const pinia = createPinia();
app.use(pinia);
app.mount("#app");
如果需要持久化就安装pinia持久化(作用是持久化到localStorage)
npm i pinia-plugin-persistedstate
在mian.js文件注册pinia持久化
import "./assets/main.css";
import { createApp } from "vue";
import App from "./App.vue";
import { createPinia } from "pinia";
import piniaPluginPersistedstate from "pinia-plugin-persistedstate";
const app = createApp(App);
const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);
app.use(pinia);
app.mount("#app");
创建stores文件夹,创建web.js文件

web.js文件代码
import { defineStore } from "pinia";
import { reactive, ref } from "vue";
export const useWebStore = defineStore(
"web",
() => {
const users = ref(100);
const web = reactive({ name: "张三", age: 14 });
const userAdd = () => {
users.value++;
};
return {
users,
web,
userAdd,
};
},
{
persist: true,
}
);
App.vue文件代码
<script setup>
import { useWebStore } from "./stores/web.js";
const webStore = useWebStore();
</script>
<template>
<p>姓名:</p>
<p>{{ webStore.web.name }}</p>
<p>年龄:</p>
<p>{{ webStore.web.age }}</p>
<br />
<p>{{ webStore.users }}</p>
<br />
<button @click="webStore.userAdd()">加一</button>
</template>