Vue 3 状态管理:Pinia基本使用

262 阅读2分钟

在 Vue 3 中进行状态管理,Pinia 是一个轻量且强大的替代品,替代了 Vuex。本文将详细介绍如何在 Vue 3 项目中使用 Pinia 进行状态管理。

Pinia 简介

Pinia 是 Vue 核心团队维护的状态管理库,灵感来源于 Vuex,但相较于 Vuex 更加简洁易用。Pinia 支持 Vue 3 的组合式 API 和 TypeScript,是管理 Vue 应用状态的理想选择。

安装 Pinia

要在 Vue 3 项目中使用 Pinia,首先需要进行安装:

npm install pinia

然后在 Vue 项目的入口文件中进行配置,通常是 main.jsmain.ts

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')

创建一个基本的 Store

在 Pinia 中,Store 就是用来管理状态的。创建一个 Store 非常简单,以下是一个基本的例子:

src/stores/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  
  function increment() {
    count.value++
  }
  
  return { count, increment }
})

使用 Store

创建好 Store 之后,我们就可以在组件中使用它:

<template>
  <div>
    <p>{{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script setup>
import { useCounterStore } from '@/stores/counter'

const counterStore = useCounterStore()
const { count, increment } = storeToRefs(counterStore)
</script>

状态(State)

状态是存储在 Store 中的数据,可以通过 Store 实例直接访问和修改:

const counterStore = useCounterStore()
console.log(counterStore.count.value) // 输出当前的 count 值
counterStore.count.value = 5 // 修改 count 值

计算属性(Getters)

Getters 类似于组件中的计算属性,用于对状态进行派生计算:

// src/stores/counter.js
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  
  const doubleCount = computed(() => count.value * 2)

  function increment() {
    count.value++
  }

  return { count, doubleCount, increment }
})

在组件中使用 Getters:

<template>
  <div>
    <p>Double Count: {{ doubleCount }}</p>
  </div>
</template>

<script setup>
import { useCounterStore } from '@/stores/counter'
import { storeToRefs } from 'pinia'

const counterStore = useCounterStore()
const { doubleCount } = storeToRefs(counterStore)
</script>

动作(Actions)

Actions 是用来修改状态的方法,支持异步操作:

// src/stores/counter.js
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)

  function increment() {
    count.value++
  }

  async function fetchCountFromServer() {
    const response = await fetch('https://api.example.com/count')
    const data = await response.json()
    count.value = data.count
  }

  return { count, increment, fetchCountFromServer }
})

插件(Plugins)

Pinia 也支持插件,可以扩展其功能。例如,使用插件来持久化状态:

import { createPersistedState } from 'pinia-plugin-persistedstate'

const pinia = createPinia()
pinia.use(createPersistedState())

Pinia 提供了一个简洁且强大的方式来进行 Vue 3 状态管理。希望这篇教程对你有所帮助!