状态管理库——Pinia

Pinia 是一个基于 Vue.js 的状态管理库,特别是为 Vue 3 设计,旨在提供一种简单、直观且类型安全的方式来管理 Vue.js 应用的状态。以下是 Pinia 的基本用法:

1. 安装 Pinia

npm install pinia # 或者

yarn add pinia

2. 创建 Pinia 实例

在你的 Vue 应用中(通常在 main.js 或 main.ts 文件中),你需要创建一个 Pinia 实例,并将其添加到 Vue 应用中:

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

3. 定义 Store

使用 defineStore 函数来定义你的状态仓库(Store)。这个函数接受两个参数:store 的 ID 和一个包含 store 选项的对象(如 state、getters、actions 等)。

import { defineStore } from 'pinia'  
  
export const useUserStore = defineStore('user', {  
  state: () => ({  
    name: 'John Doe',  
    age: 30  
  }),  
  getters: {  
    // 计算属性,基于 state 的数据返回一些值  
    userNameWithAge(state) {  
      return `${state.name} (${state.age})`  
    }  
  },  
  actions: {  
    // 定义改变 state 的逻辑  
    incrementAge() {  
      this.age++  
    }  
  }  
})

4. 在组件中使用 Store

在 Vue 组件中,你可以通过 useStore 函数(这里的函数名基于你定义的 Store 名字,如 useUserStore)来获取 Store 的实例,并访问其 state、getters 和 actions。

<template>  
  <div>  
    <p>{{ userStore.name }}</p>  
    <p>{{ userStore.age }}</p>  
    <p>{{ userStore.userNameWithAge }}</p>  
    <button @click="incrementAge">Increment Age</button>  
  </div>  
</template>  
  
<script setup>  
import { useUserStore } from './stores/userStore'  
  
const userStore = useUserStore()  
  
function incrementAge() {  
  userStore.incrementAge()  
}  
</script>

5. 响应式处理

当你从 Store 中解构出状态时,你需要使用 storeToRefs 或类似方法来保持其响应性,否则状态将失去响应性。

import { storeToRefs } from 'pinia'  
  
const { name, age } = storeToRefs(userStore)

  • 14
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值