Pinia简单使用

安装

# 使用 yarn
yarn add pinia
# 或者使用 npm
npm install pinia

使用

  1. 创建一个js文件store/counter.js
import { defineStore } from 'pinia'

// 第一个参数 counter 是应用中 Store 的唯一ID
export const useCounterStore = defineStore('counter', {
    state: ()=>({
        count: 0,
        name: 'demo'
    }),
    getters: {
        doubleCount: (state)=> state.count*2
    },
    actions: {
        increment() {
            this.count++
        }
    }
})
  1. 组件内使用demo.vue
<template>
  <div>
    <div>count:{{ count }}</div>
    <div>doubleCOunt:{{ doubleCount }}</div>
    <button @click="add">按钮</button>
  </div>
</template>
<script setup>
import { computed } from 'vue'
import { useCounterStore } from '@/store/counter'

const store = useCounterStore()

// 不可以这样直接解构,会破坏响应式
// const { name, doubleCount } = store

// 获取state的值
const count = computed(()=>store.count)

// 获取getters的值
const doubleCount = computed(()=>store.doubleCount)

// 调用actions修改count
const add = () => {
  store.increment()
}
</script>

页面效果

初始效果
在这里插入图片描述
点击按钮后
在这里插入图片描述

Pinia 是 Vue.js 的状态管理库,它用于管理组件间共享的状态。其设计灵感来自于 Vuex 4,但更加简洁和模块化。Pinia 可以被看作是 Vuex 的替代方案,但其核心思想是提供一个简单、轻量、但同时具备Vuex核心特性的状态管理解决方案。 使用 Pinia 主要包含以下几个步骤: 1. 安装 Pinia: 你可以通过 npm 或 yarn 来安装 Pinia。 ```bash npm install pinia # 或者 yarn add pinia ``` 2. 创建一个 Pinia store: 在你的 Vue 应用中,你可以创建一个或多个 store 来管理状态。每个 store 都是一个带有状态(state)、getter、actions 的对象。 ```javascript import { defineStore } from 'pinia'; export const useCounterStore = defineStore('counter', { state: () => ({ count: 0, }), actions: { increment() { this.count++; }, }, getters: { doubleCount: (state) => state.count * 2, }, }); ``` 3. 在组件中使用 store: 在 Vue 组件中,你可以通过 `useStore` 方法来访问和操作 store 中的状态和方法。 ```javascript <template> <div> <p>Count: {{ store.count }}</p> <button @click="store.increment">Increment</button> </div> </template> <script> import { useCounterStore } from '@/stores/counter'; export default { setup() { const store = useCounterStore(); return { store }; }, }; </script> ``` 4. 启用 Pinia: 最后,需要将 Pinia 添加到 Vue 应用中。 ```javascript import { createApp } from 'vue'; import { createPinia } from 'pinia'; import App from './App.vue'; import { useCounterStore } from '@/stores/counter'; const app = createApp(App); const pinia = createPinia(); app.use(pinia); app.mount('#app'); ``` 通过以上步骤,你就可以在 Vue 应用中使用 Pinia 来管理状态了。Pinia 提供了响应式的状态管理,使得状态的跟踪和调试更加方便。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

来一颗砂糖橘

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

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

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

打赏作者

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

抵扣说明:

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

余额充值