全书目录

第三篇:Vue 完全指南 —— 新城区商业街宇宙

第十五章:Pinia —— 市政总台账

1 分钟 120 字 第 85 / 962 个阅读单元

局部状态放组件里。跨组件、跨页面、需要统一调试的状态,交给 Pinia

ts
// 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,
  };
});
vue
<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 特别像城市政务大厅