1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
| import { watch, watchEffect, ref, reactive } from 'vue'
function useSmartWatch(source, callback, options = {}) { const { deep = false, immediate = false, debounce = 0 } = options let timeoutId = null const debouncedCallback = (...args) => { if (debounce > 0) { clearTimeout(timeoutId) timeoutId = setTimeout(() => callback(...args), debounce) } else { callback(...args) } } return watch(source, debouncedCallback, { deep, immediate }) }
function useConditionalWatch(source, callback, condition) { return watch( source, (newValue, oldValue) => { if (condition(newValue, oldValue)) { callback(newValue, oldValue) } } ) }
function useBatchWatch(sources, callback, options = {}) { const { batchSize = 10, delay = 100 } = options const changes = [] let timeoutId = null const flushChanges = () => { if (changes.length > 0) { callback([...changes]) changes.length = 0 } } sources.forEach((source, index) => { watch(source, (newValue, oldValue) => { changes.push({ index, newValue, oldValue }) if (changes.length >= batchSize) { clearTimeout(timeoutId) flushChanges() } else { clearTimeout(timeoutId) timeoutId = setTimeout(flushChanges, delay) } }) }) return flushChanges }
const formData = reactive({ name: '', email: '', phone: '', address: '' })
useSmartWatch( formData, (newData) => { console.log('表单数据变化:', newData) saveDraft(newData) }, { deep: true, debounce: 500 } )
useConditionalWatch( () => formData.email, (newEmail) => { console.log('邮箱验证:', newEmail) validateEmail(newEmail) }, (newEmail) => newEmail && newEmail.includes('@') )
function useWatchWithCleanup(source, callback) { let cleanup = null const stopWatcher = watch( source, async (newValue, oldValue, onCleanup) => { if (cleanup) { cleanup() } cleanup = await callback(newValue, oldValue) onCleanup(() => { if (cleanup) { cleanup() cleanup = null } }) } ) return stopWatcher }
const searchQuery = ref('') const suggestions = ref([])
useWatchWithCleanup( searchQuery, async (query) => { if (!query.trim()) { suggestions.value = [] return null } const controller = new AbortController() try { const response = await fetch(`/api/search?q=${query}`, { signal: controller.signal }) const data = await response.json() suggestions.value = data.suggestions } catch (error) { if (error.name !== 'AbortError') { console.error('搜索失败:', error) } } return () => { controller.abort() } } )
|