实现vue3中的pinia中的数据响应式

第一种方式

使用storeToRefs

import { publicStore } from "@/store";
import { storeToRefs } from 'pinia'
const store = publicStore();
let { collapsed } = storeToRefs(store);

第二种方法

使用toRefs

import {ref, toRefs} from 'vue';
import { publicStore } from "@/store";
import { storeToRefs } from 'pinia'
const store = publicStore();
let { collapsed } = toRefs(store);

第三种方法

使用computed

import {ref, computed} from 'vue';
import { publicStore } from "@/store";
import { storeToRefs } from 'pinia'
const store = publicStore();
const collapsed = computed(() => store.collapsed);

### 如何在 UniApp Vue3 项目中使用 Pinia 实现状态管理 #### 创建并初始化 Pinia Store 为了使 Pinia 能够正常工作,在 `main.js` 文件中需要引入必要的依赖项,并设置好应用实例以便能够访问到 Pinia 提供的状态管理功能[^2]。 ```javascript // main.js import { createSSRApp } from &#39;vue&#39;; import App from &#39;./App.vue&#39;; // 导入 Pinia 及其插件用于持久化存储 import { createPinia } from &#39;pinia&#39;; import { createUnistorage } from &#39;pinia-plugin-unistorage&#39;; export function createApp() { const app = createSSRApp(App); // 创建一个新的 Pinia 实例 const pinia = createPinia(); // 使用 unistorage 插件来启用持久化特性 pinia.use(createUnistorage()); // 将 Pinia 注册至应用程序上下文中 app.use(pinia); return { app }; } ``` 这段代码展示了如何通过调用 `createPinia()` 方法创建一个 Pinia 实例,接着利用 `.use()` 方法挂载上持久化插件 `pinia-plugin-unistorage`,最后再把整个 Pinia 库注册给 Vue 应用程序实例以备后续组件内调用[^4]。 #### 定义 State 和 Actions 定义 store 中的数据结构以及操作这些数据的方法。通常会在单独文件夹下按照业务逻辑划分多个 stores 文件,这里仅展示最基础的例子: ```typescript // src/stores/counterStore.ts import { defineStore } from &#39;pinia&#39;; export const useCounterStore = defineStore(&#39;counter&#39;, { state: () => ({ count: 0, }), actions: { increment() { this.count++; }, decrement() { if (this.count > 0) { this.count--; } } } }); ``` 上述 TypeScript 版本的代码片段说明了怎样基于 `defineStore` 函数构建名为 `&#39;counter&#39;` 的 store 对象,其中包含了初始状态 (`state`) 和改变该状态的动作 (`actions`)[^1]。 #### 组件内部获取 Store 数据 当完成了以上准备工作之后,就可以很方便地在一个或多个组件里读取共享的状态或是触发相应的 action 更新它们了: ```html <template> <div class="example"> Count is {{ counter }} <button @click="increment">Increment</button> <button :disabled="!canDecrement" @click="decrement">Decrement</button> </div> </template> <script setup lang="ts"> import { ref, computed } from &#39;vue&#39;; import { useCounterStore } from &#39;../stores/counterStore&#39;; const counterStore = useCounterStore(); let counter = ref(counterStore.count); function increment() { counterStore.increment(); } const canDecrement = computed(() => counter.value !== 0); function decrement() { counterStore.decrement(); } </script> ``` 在这个例子中,模板部分绑定了按钮点击事件处理器去执行增减计数器的操作;而在 `<script>` 部分,则是从之前定义好的 `counterStore` 获取当前数值并通过响应式的变量绑定到了视图层面上显示出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大可-

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值