在 Vue.js 開發的動態環境中,在單個組件中處理復雜的業務邏輯可能會導致笨重的文件和維護噩夢。雖然 Pinia 提供集中式狀態管理,但僅依賴它來處理復雜的業務邏輯可能會導致代碼混亂。本文探討了使用 Composition API 的替代方法,說明開發人員如何將數據和邏輯封裝在自定義 hooks 中以實現高效的狀態管理。
駕馭復雜的業務邏輯
在日常開發中,經常會出現功能變得過于復雜而無法限制在單個 Vue.js 組件中的情況。分解組件是合乎邏輯的解決方案,但這帶來了在組件之間共享數據和業務邏輯的挑戰。雖然 Pinia 在這方面很受歡迎,但如果廣泛用于所有復雜的業務邏輯,它就會變得不堪重負。
擁抱 Composition API 和自定義 Hook
一個引人注目的替代方案是利用 Composition API 將數據和業務邏輯封裝在自定義 hooks 中。這些鉤子(以 useStore
函數為例)成為狀態定義、更新和特定業務邏輯的中心。反過來,組件只需要與這些鉤子公開的狀態和方法進行交互,從而抽象出內部的復雜性。
// 使用 Composition API 自定義 hook
import { computed, ref } from "vue";// 在 useStore 函數外部定義 count 變量
const count = ref(0);
const doubleCount = computed(() => {return count.value * 2;
});export const useStore = () => {function increment() {count.value = count.value + 1;}function decrement() {count.value = count.value - 1;}return {count,doubleCount,increment,decrement,};
};
孤立的 Hook 調用的陷阱
當 CountValue
和 CountBtn
等組件在其 setup 函數中獨立調用 useStore
掛鉤時,就會出現挑戰。本文揭示了每次調用時創建 count
變量的獨立實例的陷阱,從而導致組件之間的狀態更新不一致。
// CountValue.vue component
<template><p>count's value is {{ count }}</p><p>doubleCount's value is {{ doubleCount }}</p>
</template><script setup lang="ts">
import { useStore } from "./store";// 對 useStore 的獨立調用創建獨立的 count 實例
const { count, doubleCount } = useStore();
</script>// CountBtn.vue component
<template><button @click="decrement">count--</button><button @click="increment">count++</button>
</template><script setup lang="ts">
import { useStore } from "./store";// 對 useStore 的獨立調用創建獨立的 count 實例
const { decrement, increment } = useStore();
</script>
協調組件之間的狀態
為了克服這一挑戰,一種優化方法是將 count
變量的定義重新定位到 useStore
函數之外。這可確保調用 useStore
hook 的所有組件共享 count
變量的同一實例,從而促進同步狀態管理。
// 將計數定義移至 useStore 函數之外
import { computed, ref } from "vue";const count = ref(0);
const doubleCount = computed(() => {return count.value * 2;
});export const useStore = () => {function increment() {count.value = count.value + 1;}function decrement() {count.value = count.value - 1;}return {count,doubleCount,increment,decrement,};
};
在 Pinia 似乎難以應對復雜業務邏輯的各個方面的情況下,Composition API 提供了一個干凈、有組織的替代方案。通過將數據和邏輯封裝在自定義鉤子中,開發人員可以在 Vue.js 應用程序中的模塊化和高效狀態管理之間取得平衡。
本文強調了 Composition API 在構建 Vue.js 解決方案中的多功能性,以最大限度地提高靈活性和可維護性。通過采用自定義鉤子,開發人員可以編寫符合 Vue.js 原則的有組織、可讀的代碼。
原文:https://blog.stackademic.com/vue-3-you-dont-need-pinia-in-some-scenarios-with-the-composition-api-79fc4ff6ab8f