跳到主要内容

Pinia

Pinia 起始于 2019 年 11 月左右的一次实验,其目的是设计一个拥有组合式 API 的 Vue 状态管理库。

先创建一个 Store:

// stores/counter.js
import { defineStore } from "pinia";

export const useCounterStore = defineStore("counter", {
state: () => ({ count: 0 })

actions: {
increment() {
this.count++;
},
},
});

然后你就可以在一个组件中使用该 store 了:

<template>
<!-- 直接从 store 中访问 state -->
<div>Current Count: {{ counter.count }}</div>
</template>

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

const counter = useCounterStore();

counter.count++;

// 自动补全! ✨
counter.$patch({ count: counter.count + 1 });

// 或使用 action 代替
counter.increment();
</script>