Pinia+Vue3使用案例及Pinia持久化存储

为什么要使用Pinia

Pinia是Vue的一个存储库,它允许你跨组件/页面共享状态。 如果你熟悉Composition API,你可能会认为你已经可以通过一个简单的导出const state = reactive({})来共享一个全局状态。 这对于单页应用程序是正确的,但如果是服务器端呈现,则会暴露应用程序的安全漏洞。 但即使是在小的单页应用程序中,你也可以通过使用Pinia获得很多:

  • 热模块替换
  • 修改存储而无需重新加载页面
  • 在开发过程中保持任何现有状态
  • 使用插件扩展Pinia功能
  • 为JS用户提供正确的TypeScript支持或自动补全
  • 服务器端渲染支持

安装

 npm install pinia

配置

新建sotre仓库
index.ts
import type { App } from "vue";
import { createPinia } from "pinia";

const store = createPinia();

export function setupStore(app: App<Element>) {
  app.use(store);
}

export { store };
以premession.ts模块为例
import { defineStore } from "pinia";
import { store } f
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于持久存储 Vue 3 + TypeScript 中,你可以使用 PiniaPinia 是一个为 Vue 3 设计的状态管理库,它支持 TypeScript,并且提供了内置的插件来支持持久存储。 首先,你需要安装 Pinia: ```bash npm install pinia ``` 然后,你可以创建一个 Pinia store 并在其中定义你的状态和操作。在 store 中,你可以使用内置的 `persist` 插件来实现持久存储。这个插件将自动将你的状态保存到本地存储中,并在应用重新加载时恢复它。 ```typescript import { defineStore } from 'pinia' export const useMyStore = defineStore('myStore', { state: () => ({ count: 0, }), actions: { increment() { this.count++ }, }, plugins: [persist()], }) ``` 在上面的示例中,我们定义了一个名为 `myStore` 的 Pinia store,并添加了一个状态 `count` 和一个操作 `increment`。我们还在 `plugins` 选项中添加了 `persist()` 插件。 现在,你可以在你的 Vue 组件中使用 `useMyStore` 来访问和操作这个 store: ```vue <template> <div> <p>Count: {{ count }}</p> <button @click="increment">Increment</button> </div> </template> <script> import { defineComponent } from 'vue' import { useMyStore } from './myStore' export default defineComponent({ setup() { const myStore = useMyStore() return { count: myStore.count, increment: myStore.increment, } }, }) </script> ``` 现在,每当你点击 "Increment" 按钮时,`count` 的值将递增,并且这个值将在应用重新加载时保留下来。 这就是如何使用 Pinia 实现持久存储Vue 3 + TypeScript 中。希望能对你有所帮助!如果有任何疑问,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值