npm install pinia --save
import { createPinia } from "pinia"
const store = createPinia()
export default store
import { createApp } from 'vue'
import store from '@/store'
const app = createApp(App)
app.use(store)
app.mount('#app')
import { defineStore } from "pinia"
export const useUserStore = defineStore({
id:'user',
state() {
return {
name: '',
age: 0
}
}
})
<template>
User:{{ name }} == {{ age }}
<br>
<button @click="fun">修改值</button>
</template>
<script setup lang="ts">
import {useUserStore} from "@/store/module/user"
import {storeToRefs} from "pinia"
const userStore = useUserStore()
const {name, age} = storeToRefs(userStore)
const fun = () => {
userStore.name = "zhangsan"
userStore.age = 18
}
</script>
打开页面,单击页面按钮,显示的用户信息发生变化,刷新页面又恢复到原来的样子。
npm install pinia-plugin-persist --save
import { createPinia } from "pinia"
import piniaPluginPersist from 'pinia-plugin-persist'
const store = createPinia()
store.use(piniaPluginPersist)
export default store
import {defineStore} from "pinia"
export const useUserStore = defineStore({
id: "user",
state: () => {
return {
name: '',
age: 0
}
},
persist: {
enabled: true,
strategies: [
{
key: 'wego_user',
storage: localStorage
}
]
}
})
注:在strategies中可以指定对哪些数据进行缓存,比如:
strategies: [
{ storage: localStorage, paths: ['token','name'] }
]
运行程序,打开页面单击按钮,数据发生变化,关闭页面再次打开,页面显示的仍然是变化后的数据,此时F12,会看到:
