index.ts
需要安装pinia-plugin-persist
npm i pinia-plugin-persist -S
import { createPinia} from "pinia"
// 引入批量的pinia持久存储插件
import piniaPluginPersist from 'pinia-plugin-persist'
const store=createPinia();
store.use(piniaPluginPersist)
export default store;
user.ts
import {defineStore} from "pinia"export const useStore=defineStore('storeId',
{state:()=>{return{name:"zhangsan",num:0,age:20}},getters:{changeNum(){console.log("getters");return this.num+1000;}},actions:{upNum(val){this.num+=val;}},// 开启数据缓存persist:{enabled:true,strategies:[{key:'my_user',storage:localStorage,paths:["age"]}]}
})
main.ts:
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from "./router"
// import store from "./store"
import store from "./piniaStore"
const app = createApp(App);
app.use(router);
app.use(store);
app.mount('#app')
在页面中使用:
<template><div>name: {{ name }} <br />num: {{ num }}</div><p>changeNum:{{ changeNum }}</p><button @click="updateName">修改姓名</button><button @click="addBtn">+操作</button>
</template><script setup lang="ts">
import { storeToRefs } from "pinia";
import { useStore } from "@/piniaStore/user";
const store = useStore();
console.log(store);
let { num, name, changeNum } = storeToRefs(store);const updateName = () => {// name.value = "李四";// 批量修改store.$patch((state) => {state.num++;state.name = "赵四";});
};const addBtn = () => {store.upNum(200);
};
defineExpose({num,name,changeNum,
});
</script><style></style>
效果图: