uniapp pinia 永久存储
时间: 2025-07-02 08:43:04 浏览: 8
### 如何在 UniApp 中使用 Pinia 实现数据的永久存储
#### 创建 Pinia Store 并启用持久化功能
为了实现 Pinia 数据的永久存储,在 `main.js` 文件中引入并配置 Pinia 插件:
```javascript
// main.js
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
export default function (Vue) {
const app = createSSRApp(Vue)
app.use(pinia)
}
```
此设置确保了 Pinia 存储的数据能够被持久保存[^1]。
#### 定义带有持久化的 State
创建一个新的 store 或者修改现有的 store 来定义哪些 state 需要持久化。下面的例子展示了如何创建一个名为 `counterStore` 的 store,并指定其部分或全部 state 进行持久化处理:
```typescript
// stores/counter.ts
import { defineStore } from 'pinia'
import { persistedState } from 'pinia-plugin-persistedstate'
export const useCounterStore = defineStore({
id: 'counter',
state: () => ({
count: 0,
name: ''
}),
plugins: [persistedState()]
})
```
上述代码片段设置了整个 state 对象都将被持久化到本地存储中。
如果只需要特定字段保持持久,则可以在调用 `persistedState()` 方法时传递选项对象来定制行为:
```typescript
plugins: [
persistedState({
key: 'my-app-counter-store', // 自定义键名,默认会基于store ID生成
paths: ['count'] // 只保留这些路径下的属性值
})
]
```
这样就只会在浏览器关闭后仍然记住 `count` 属性的变化情况,而不会影响其他未列出的状态项。
#### 使用 Store 在组件内读取和写入数据
一旦完成了以上配置工作,就可以像平常一样正常使用这个 store 了。当访问页面刷新之后,之前设定好的状态也会自动恢复过来。
```html
<template>
<div>
Count is {{ counter.count }}
Name is {{ counter.name }}
<button @click="increment">Increment</button>
<input v-model="newName" placeholder="Enter your name">
<button @click="setName">Set Name</button>
</div>
</template>
<script setup lang="ts">
import { ref, computed } from 'vue'
import { useCounterStore } from '@/stores/counter'
const newName = ref('')
const counter = useCounterStore()
function increment() {
counter.count++
}
function setName() {
counter.name = newName.value.trim()
}
</script>
```
在这个例子中,每当点击按钮增加计数器数值或是输入名字再按下“设为名称”的时候,更改后的值会被立即同步至本地缓存里去;即使重新加载网页也不会丢失已有的记录。
阅读全文
相关推荐


















