vue学习 之 pinia 和 piniapersist使用

Pinia 是 Vue.js 的状态管理库,它在 Vue 3 中得到了原生支持。Pinia 是基于 Composition API 设计的,相比于 Vue 2 的 Vuex,Pinia 更简洁、更容易使用,并且拥有了更好的 TypeScript 支持。 要使用 Pinia,首先需要安装它: ```bash npm install pinia ``` 然后,在你的 Vue 3 应用中引入并使用 Pinia: ```javascript import { createApp } from 'vue' import { createPinia } from 'pinia' import App from './App.vue' const app = createApp(App) // 创建 Pinia 实例 const pinia = createPinia() // 将 Pinia 实例添加到 Vue 应用中 app.use(pinia) app.mount('#app') ``` 接下来,你可以定义你的 store。一个基本的 Pinia store 包含了状态、getters、actions 和选项: ```javascript // src/stores/counter.js import { defineStore } from 'pinia' export const useCounterStore = defineStore('counter', { state: () => { return { count: 0 } }, getters: { doubleCount: (state) => state.count * 2, }, actions: { increment() { this.count++ }, }, }) ``` 在组件中使用 store 的步骤如下: ```vue <template> <div> <p>Count is: {{ counterStore.count }}</p> <p>Double count is: {{ counterStore.doubleCount }}</p> <button @click="counterStore.increment">Increment</button> </div> </template> <script> import { defineComponent } from 'vue' import { useCounterStore } from '../stores/counter' export default defineComponent({ setup() { const counterStore = useCounterStore() return { counterStore, } }, }) </script> ``` 通过以上步骤,你可以在 Vue 3 应用中成功地使用 Pinia 进行状态管理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值