Vue3之Composables

码农小哥。發表於2024-03-18

前言

Composables 稱之為可組合項,熟悉 react 的同學喜歡稱之為 hooks ,由於可組合項的存在,Vue3 中的元件之間共享狀態比以往任何時候都更容易。這種新範例引入了一種更有組織性和可擴充套件性的方式來管理整個應用程式的狀態和邏輯。

什麼是Composables

本質上,可組合項是一種模式而不是特定的功能。它是透過一個簡單的函式來實現的,該函式可以儲存狀態和可重用的程式碼。總的來說:可組合項是可重用的有狀態函式。它們可用於在元件之間共享響應式狀態和邏輯。

如何定義

下面透過一段程式碼看看什麼是可組合項:

import { ref } from 'vue';

// 定義可組合項需以use開頭 比如 useXXX
export function useCounter(initialValue = 0) {
// 可組合項都有自己的生命週期 你完全可以使用Composition API
const counter = ref(initialValue);

function increment() {
counter.value++;
}

function decrement() {
counter.value--;
}

function reset() {
counter.value = initialValue;
}
// 返回其他元件需要訪問的所有內容。
return { counter, increment, decrement, reset };
}

我們將 counter 宣告為響應式狀態以及三個操作它的函式,請注意,可組合項必須返回其他元件可以訪問的所有內容。

如何使用

從元件方面,我們可以像這樣匯入和初始化可組合項:

<template>
<div>
<h3>Counter Value: {{ counter }}</h3>
<button @click="increment">Increment</button>
<button @click="decrement">Decrement</button>
<button @click="reset">Reset</button>
</div>
</template>

<script setup>
import { useCounter } from './useCounter';

const { counter, increment, decrement, reset } = useCounter();
</script>

使用可組合項進行共享狀態

在某些情況下,需要例項之間共享狀態,我們知道 Vue3 中元件通訊方式有很多種比如 props,emits,provide甚至一些狀態管理庫比如 pinia。其實可組合項也可以達到同樣的目的,可以透過在可組合函式外部宣告狀態來實現:

import { ref } from 'vue';

// 外部進行宣告狀態
const sharedState = ref();

export function useComposable() {
// 內部宣告狀態每次都會初始化
const localState = ref();

return { sharedState, localState };
}

這種方法展示了可組合性的靈活性,讓我們能夠以對每個例項單獨或在它們之間共享的方式管理狀態。

總結

總而言之,可組合性透過提供自然且易於理解的簡單性和模組化性,真正重新定義了 Vue3。它們可用於從元件中抽象出複雜性,還可在元件之間共享狀態。強烈推薦大家運用起來。

相關文章