状态管理工具Pinia使用笔记 | 青训营

104 阅读1分钟

Pinia 是一个用于 Vue.js 的状态管理库,它提供了一种简单而强大的方式来管理应用程序的状态。

项目中安装

npm install -S pinia

创建 Pinia 实例

首先,在 stores 目录下创建一个新的文件,例如 counter.js。在该文件中可以定义一个计数器状态存储对象:

import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0
  }),
  actions: {
    increment() {
      this.count++
    },
    decrement() {
      this.count--
    }
  }
})

在上面的代码中使用 defineStore 函数来创建一个名为 counter 的状态存储对象。state 函数返回了一个包含 count 属性的对象,初始值为 0actions 属性包含了两个方法 increment 和 decrement,用于增加和减少计数器的值。

在组件中使用状态

创建一个名为 Counter.vue 的组件来展示计数器的值和按钮来增加或减少计数器的值。

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

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

export default {
  setup() {
    const counterStore = useCounterStore()

    return {
      count: counterStore.count,
      increment: counterStore.increment,
      decrement: counterStore.decrement
    }
  }
}
</script>

在上面的代码中,导入了 useCounterStore 函数,然后在 setup 函数中创建了一个 counterStore 实例。我们将 count 属性和 incrementdecrement 方法暴露给模板,以便在模板中使用。

在应用程序中注册状态

在根组件中注册状态存储对象。可以在 App.vue 文件中添加以下代码:

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

export default {
  setup() {
    const pinia = usePinia()
    pinia.useStore(useCounterStore)

    return {}
  }
}
</script>

使用 usePinia 函数来获取 Pinia 实例,并使用 useStore 方法注册 useCounterStore

参考资料

Home | Pinia 中文文档 (web3doc.top)