vue3+ts pinia存储及持久化
2023-12-26 06:25:55
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>
效果图:
文章来源:https://blog.csdn.net/weixin_45932157/article/details/135211917
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!