一、安装pinia
npm i pinia
二、全局注册
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import './style.css'
import App from './App.vue'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
const app = createApp(App)
app.use(pinia)
app.mount('#app')
三、定义仓库
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
// 定义状态
state: () => ({
count: 0,
name: 'Eduardo',
field1: 'some data',
field2: 'other data'
}),
// 持久化配置
persist: {
key: 'counter-data',
storage: localStorage,
},
// 计算属性
getters: {
doubleCount: (state) => state.count * 2,
doubleCountPlus: (state) => state.count * 2 + 10
},
// 方法
actions: {
increment() {
this.count++
},
decrement() {
this.count--
},
incrementByAmount(amount) {
this.count += amount
},
// 添加一个重置方法用于测试
reset() {
this.count = 0
this.name = 'Eduardo'
this.field1 = 'some data'
this.field2 = 'other data'
}
},
})
四、使用
<template>
<div style="padding: 20px; border: 1px solid blue;">
<h2>计数器测试 (CounterTest)</h2>
<p>计数值: {{ counterStore.count }}</p>
<p>双倍计数: {{ counterStore.doubleCount }}</p>
<p>名称: {{ counterStore.name }}</p>
<div style="margin: 10px 0;">
<button @click="counterStore.increment()">+1</button>
<button @click="counterStore.decrement()">-1</button>
<button @click="counterStore.incrementByAmount(5)">+5</button>
<button @click="updateName">更新名称</button>
</div>
<div>
<input v-model="counterStore.count" type="number" placeholder="直接编辑计数" />
</div>
<div style="margin-top: 20px;">
<h3>本地存储检查</h3>
<p>localStorage中的值: {{ localStorageValue }}</p>
<p>Store的持久化配置: {{ persistConfig }}</p>
<button @click="refreshPage">刷新页面测试持久化</button>
</div>
</div>
</template>
<script setup>
import { useCounterStore } from '../stores/counter.js'
import { ref, onMounted, computed } from 'vue'
const counterStore = useCounterStore()
const localStorageValue = ref('')
const persistConfig = ref('')
const updateName = () => {
counterStore.name = `访客${Math.floor(Math.random() * 100)}`
}
const refreshPage = () => {
window.location.reload()
}
onMounted(() => {
// 读取localStorage中的值以检查是否正确保存
const storedValue = localStorage.getItem('counter-data')
localStorageValue.value = storedValue ? JSON.parse(storedValue).state : '未找到'
// 检查store的持久化配置
persistConfig.value = counterStore.$persist ? '已配置' : '未配置'
// 打印整个store状态
console.log('Store State:', counterStore.$state)
console.log('Persist Info:', counterStore.$persist)
})
</script>