Vue3-Pinia的简单使用 - 19

Vue3中需要对状态进行公共管理,所以也需要使用 Vuex 的升级版 Pinia,其相比Vuex更加简洁方便,无需 mutations

1. 安装 Pinia

npm install pinia

 在 main.js 中引入,并使用,需要用 Vue3 的 链式调用

import { createPinia } from 'pinia'
createApp(App).use(createPinia()).mount('#app')

2. 配置 Pinia 的 Store 

从 pinia 中引入 defineStore ,对 Pinia 的 state 和 actions 进行初步设置

state:公共仓库的数据

actions:更改仓库数据的方法

import { defineStore } from "pinia";

const useCounterStore = defineStore('counterStore', {
    state() {
        return {
            count: 666
        }
    },

    actions: {
        add() {
            this.count++
        }
    }
})

export default useCounterStore

3. 组件中使用 Pinia

需要引入 Pinia 进行公共数据管理的组件,引入 store ,并且调用这个函数

import useCounterStore from "../store/counterStore";
const counterStore = useCounterStore();

使用 state:

import { storeToRefs } from "pinia";
// 解构state数据  解构完了后会失去响应式 ,需要去pinia里面引入 storeToRefs
const { count } = storeToRefs(counterStore);
 <div>{{ count }}</div>

正常直接调用出state也行,例如 {{counterStore.state}}  但是代码麻烦,所以解构出来方便,但是解构完的 state又会失去响应式,所以还需要对其重新赋予响应式,从 pinia 里面引入 storeToRefs ,将其 state 的数据重新转换为响应式

使用actions:

// 解构actions的方法
const add = counterStore.add;
    <button @click="add">add</button>

 

### 总结:Pinia 比起 Vuex 省略了 mutations 的功能,去更改公共管理数据更加简洁方便,任何组件都可以直接从 Pinia 中获取数据,修改数据

PS:个人感觉,你说 Vuex 弱化了 Redux 的 Reducer功能,将其异步的处理逻辑单独分出来用actions 来实现,后面 Redux 也来 Redux-thunk / Redux-saga 重新补回了这个异步处理的功能,包括 Dva.js 一样也是,好家伙,现在 Pinia 又重新回去了,变成了 Redux 的样子,来来回回,挺有意思的

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue Pinia 是一个基于 Vue 3 的状态管理库,可以让你更方便地管理应用程序的状态。下面是一个简单的例子,展示如何使用 Vue Pinia: 1. 安装 Vue Pinia ```bash npm install @pinia/vue3 ``` 2. 创建一个 store ```javascript import { defineStore } from '@pinia/vue3' export const useCounterStore = defineStore({ id: 'counter', state: () => ({ count: 0 }), actions: { increment() { this.count++ } } }) ``` 上面的代码创建了一个名为 `useCounterStore` 的 store,用于管理一个名为 `count` 的状态,并且提供了一个名为 `increment` 的 action,用于增加 `count` 的值。 3. 在组件使用 store ```vue <template> <div> <p>Count: {{ count }}</p> <button @click="increment">Increment</button> </div> </template> <script> import { useCounterStore } from './store' export default { setup() { const counterStore = useCounterStore() return { count: counterStore.count, increment: counterStore.increment } } } </script> ``` 在组件使用 `useCounterStore`,并且将 `count` 和 `increment` 绑定到组件的模板。 4. 在应用程序注册 store ```javascript import { createApp } from 'vue' import App from './App.vue' import { createPinia } from '@pinia/vue3' import { useCounterStore } from './store' const app = createApp(App) const pinia = createPinia() pinia.useStore(useCounterStore) app.use(pinia) app.mount('#app') ``` 在应用程序注册 `useCounterStore`,并将其添加到 `pinia` 实例。 以上就是使用 Vue Pinia 的一些基本步骤。通过使用 Vue Pinia,你可以轻松地管理应用程序的状态,提高开发效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值