Vue3 使用pinia+pinia-plugin-persist setup写法
vue3 pinia 数据持久化
·
最近项目技术更新,决定用vitejs+vue3+pinia重写项目。我们决定一步到位直接script setup方式来写,边学边写边记录:
1、先安装
npm i pinia-plugin-persist
2、main.ts中引入
import {createPinia} from 'pinia'
import App from './App.vue'
import router from './router/index'
import piniaPersistPlugin from 'pinia-plugin-persist'
const app = createApp(App)
const pinia = createPinia()
pinia.use(piniaPersistPlugin)
app.use(pinia)
app.use(router)
app.mount('#app')
3、新建store/index.ts,然后添加store的总管理脚本:
//import { storeToRefs } from 'pinia'
import appStore from './modules/appStore'
//import userStore from './modules/userStore'
export default {
appStore,
// userStore,
}
4 、在store文件夹下创建:/modules/appStore.ts文件:
import {defineStore} from 'pinia'
import {ref} from 'vue'
import loginStore from './loginStore'
const useAppStore = defineStore(
'appStore',
() => {
let loadNum = ref(0)
const hideLoading = () => {
loadNum.value--
}
const showLoading = () => {
loadNum.value++
}
const isLoading = () => {
return loadNum.value > 0
}
return {
hideLoading,
showLoading,
isLoading
// loadNum要持久化保存到本地一定要加,当然不加数据响应是没问题的,isLoading也会重新计算,就是不会保存
}
}
//作为第三个参数配置
// {
// persist: {
// enabled: true,
// strategies: [{storage: localStorage, paths: ['loadNum']}]
// }
// }
)
export default {
loginStore,
useAppStore
}
5、ui上的使用
<template>
<button @click="onButton">点击增加</button>
</template>
<script lang="ts" setup>
import store from '@/store'
const appStore = store.useAppStore()
const onButton = () => {
appStore.showLoading() //调用
}
</script>
<style lang="scss" scoped></style>
6、看效果
点击之后
更多推荐
已为社区贡献3条内容
所有评论(0)