局部状态放组件里。跨组件、跨页面、需要统一调试的状态,交给 Pinia。
// stores/district.ts
import { ref, computed } from 'vue';
import { defineStore } from 'pinia';
export const useDistrictStore = defineStore('district', () => {
const districtName = ref('新城区 A');
const shops = ref([
{ id: 1, name: 'Vue 书店', open: true },
{ id: 2, name: 'Pinia 咖啡馆', open: false },
]);
const openCount = computed(() => shops.value.filter(s => s.open).length);
function toggleShop(id: number) {
const target = shops.value.find(s => s.id === id);
if (target) target.open = !target.open;
}
return {
districtName,
shops,
openCount,
toggleShop,
};
});<script setup lang="ts">
import { storeToRefs } from 'pinia';
import { useDistrictStore } from '@/stores/district';
const store = useDistrictStore();
const { districtName, shops, openCount } = storeToRefs(store);
const { toggleShop } = store;
</script>| Pinia 概念 | 类比 |
|---|---|
state |
市政原始台账 |
getters / computed |
汇总报表 |
actions |
市政操作指令 |
Pinia 特别像城市政务大厅。