Vue3,用組合的方式來編寫更好的代碼(1/5)
作者:前端小智
簡介:思否百萬閱讀,勵(lì)志退休后,回家擺地?cái)偟娜恕?/span>
來源:SegmentFault 思否社區(qū)
到目前為止,可組合是組織Vue 3應(yīng)用中業(yè)務(wù)邏輯的最佳方式。
它們讓你把小塊的邏輯提取到函數(shù)中,我們可以輕松地重復(fù)使用,這樣的代碼更容易編寫和閱讀。
由于這種編寫Vue代碼的方式相對較新,你可能想知道在編寫可組合代碼的最佳做法是什么。本系列教程將作為一個(gè)指南,告訴你如何編寫值得信賴且可靠組合式代碼。
以下是我們將討論的內(nèi)容。
如何使用選項(xiàng)對象參數(shù)來使組合更有配置性 使用 ref 和 unref 來使我們的論證更加靈活 讓返回值更有用的一個(gè)簡單方法 為什么從接口開始會使我們組合會更強(qiáng)大 如何使用不需要 await 的異步代碼--讓你的代碼更容易理解
什么是可組合式?
import { ref, onMounted, onUnmounted } from 'vue'
export function useMouse() {
const x = ref(0)
const y = ref(0)
function update(event) {
x.value = event.pageX
y.value = event.pageY
}
onMounted(() => window.addEventListener('mousemove', update))
onUnmounted(() => window.removeEventListener('mousemove', update))
return { x, y }
}
<template>
X: {{ x }} Y: {{ y }}
</template>
<script setup>
import { useMouse } from './useMouse';
const { x, y } = useMouse();
</script>
選項(xiàng)對象參數(shù)
// 使用一個(gè)選項(xiàng)對象
const title = useTitle('A new title', { titleTemplate: '>> %s <<' });
// Title is now ">> A new title <<"
// 使用入一長串的參數(shù)
const title = useTitle('A new title', '>> %s <<');
// Title is now ">> A new title <<"
將選項(xiàng)作為一個(gè)整體對象而不是參數(shù)傳入,給我們帶來一些好處。
以可組合的方式實(shí)施
export function useMouse(options) {
const {
asArray = false,
throttle = false,
} = options;
// ...
};
useTitle
const title = useTitle('Initial Page Title');
// Title: "Initial Page Title"
title.value = 'New Page Title';
// Title: "New Page Title"
它也有幾個(gè)選項(xiàng)以獲得額外的靈活性。
const titleOptions = {
titleTemplate: '>> %s <<',
observe: true,
};
const title = useTitle('Initial Page Title', {
titleTemplate: '>> %s <<',
observe: true,
});
// Title: ">> Initial Page Title <<"
title.value = 'New Page Title';
// Title: ">> New Page Title <<"當(dāng)你查看useTitle的源碼時(shí),它是這么做的:
export function useTitle(newTitle, options) {
const {
document = defaultDocument,
observe = false,
titleTemplate = '%s',
} = options;
// ...
}
useRefHistory
// Set up the count ref and track it
const count = ref(0);
const { undo } = useRefHistory(count);
// Increment the count
count.value++;
// Log out the count, undo, and log again
console.log(counter.value); // 1
undo();
console.log(counter.value); // 0
{
deep: false,
flush: 'pre',
capacity: -1,
clone: false,
// ...
}我們可以把選項(xiàng)對象作為第二個(gè)參數(shù)傳入,以進(jìn)一步配置這個(gè)可組合的行為方式,與我們之前的例子一樣。
const state = ref({});
const { undo, redo } = useRefHistory(state, {
deep: true, // 追蹤對象和數(shù)組內(nèi)部的變化
capacity: 15, // 限制我們追蹤的步驟數(shù)量
});
export function useRefHistory(source, options) {
const {
deep = false,
flush = 'pre',
eventFilter,
} = options;
// ...
}
// ...
const manualHistory = useManualRefHistory(
source,
{
// Pass along the options object to another composable
...options,
clone: options.clone || deep,
setSource,
},
);
// ...
把所有的東西集中起來
// 傳遞一個(gè) ref 值,可以工作
const countRef = ref(2);
useCount(countRef);
// 或者只給一個(gè)簡單的數(shù)字
const countRef = useRef(2);

評論
圖片
表情
