VueUse 是 Anthony Fu 的一個開源項目,它為 Vue 開發人員提供了大量適用於 Vue 2 和 Vue 3 的基本 Composition API 實用程式函數。這篇文章就來跟大家分享幾個我常用的幾個 VueUse 最佳組合,希望對大家有幫助!
(學習影片分享:vue影片教學)
Vueuse擁有大量出色的組合。但是量太大,要把它們全部看完可能會讓人抓不到重點。以下來介紹一些有用到的組合,它們如下:
onClickOutside
useFocusTrap
- ## useHead
- useStorage
- useVModel
##useDark
1、 onClickOutside
#偵測點擊非常簡單。但是,當點擊發生在一個元素之外時,如何檢測?那就有點棘手了。但使用VueUse中的 onClickOutside 元件就很容易能做到這一點。程式碼如下:
<script> import { ref } from 'vue' import { onClickOutside } from '@vueuse/core' const container = ref(null) onClickOutside(container, () => alert('Good. Better to click outside.')) </script> <template> <div> <p>Hey there, here's some text.</p> <div> <p>Please don't click in here.</p> </div> </div> </template>
為想要追蹤的container
元素建立一個
:<pre class="brush:php;toolbar:false">const container = ref(null);</pre>
然後我們用元素上的ref
屬性把它變成一個模板ref
。
<div> <p>Please don't click in here.</p> </div>
有了容器的ref
之後,我們把它和一個處理程序一起傳遞給
組合。 <pre class="brush:php;toolbar:false">onClickOutside(
container,
() => alert('Good. Better to click outside.')
)</pre>
這種可組合對於管理視窗或下拉式選單很有用。當使用者點擊下拉式選單以外的地方時,你可以關閉它。
模態框也通常會表現出這種行為。範例網址:https://stackblitz.com/edit/vue3-script-setup-with-vite-18scsl?file=src/App.vue
# 2、useFocusTrap
為了擁有可訪問的應用程序,正確地管理焦點非常重要。
沒有什麼比不小心在模態後面加上tab,並且無法將焦點回到模態更糟糕的了。這就是焦點陷阱的作用。
將鍵盤焦點鎖定在一個特定的DOM元素上,不是在整個頁面中循環,而是在瀏覽器本身中循環,鍵盤焦點只在該DOM元素中循環。 下面是一個使用VueUse的
的範例:<pre class="brush:php;toolbar:false"><script>
import { ref } from &#39;vue&#39;
import { useFocusTrap } from &#39;@vueuse/integrations/useFocusTrap&#39;
const container = ref(null)
useFocusTrap(container, { immediate: true })
</script>
<template>
<div>
<button>Can't click me</button>
<div>
<button>Inside the trap</button>
<button>Can't break out</button>
<button>Stuck here forever</button>
</div>
<button>Can't click me</button>
</div>
</template></pre>
將
設定為
true#都,焦點將會被放置在container
元素中。然後,就不可能在該容器之外的地方做標籤。
到達第三個按鈕後,再點選
tab鍵將回到第一個按鈕。 就像
onClickOutside
一樣,我們先為
const container = ref(null)
<div> <button>Inside the trap</button> <button>Can't break out</button> <button>Stuck here forever</button> </div>###然後我們把這個模板引用傳遞給###useFocusTrap###組合。 ###
useFocusTrap(container, { immediate: true });######immediate### 選項將自動把焦點設定到容器內第一個可關注的元素。 #########範例網址:https://stackblitz.com/edit/vue3-script-setup-with-vite-eocc6w?file=src/App.vue########## 3、useHead###############VueUse為我們提供了一種簡單的方法來更新我們應用程式的head 部分--頁面title、scripts和其他可能放在這裡的東西。 ######useHead 組合要求我們先設定一個插件###
import { createApp } from 'vue' import { createHead } from '@vueuse/head' import App from './App.vue' const app = createApp(App) const head = createHead() app.use(head) app.mount('#app')###一旦我們使用了這個插件,我們就可以隨心所欲地更新標題部分。在這個例子中,我們將在一個按鈕上註入一些自訂樣式。 ###
<script> import { ref } from 'vue' import { useHead } from '@vueuse/head' const styles = ref('') useHead({ // Inject a style tag into the head style: [{ children: styles }], }) const injectStyles = () => { styles.value = 'button { background: red }' } </script> <template> <div> <button>Inject new styles</button> </div> </template>###首先,我們建立一個###ref###來表示我們要注入的樣式,預設為空:###
const styles = ref('');###第二,設定###useHead### 將樣式註入到頁面中。 ###
useHead({ // Inject a style tag into the head style: [{ children: styles }], })###然後,加入註入這些樣式的方法:###
const injectStyles = () => { styles.value = 'button { background: red }' }###當然,我們不限於注入樣式。我們可以在我們的######中加入任何這些內容:#############title###########meta tags## ##########link tags############base tag############style tags########## ##script tags############html attributes#############body attributes##############事例位址: https://stackblitz.com/edit/vue3-script-setup-with-vite-szhedp?file=src/App.vue#########4、useStorage########## useStorage###真的很酷,因為它會自動將###ref### 同步到 localstorage,事例如下:###
<script> import { useStorage } from '@vueuse/core' const input = useStorage('unique-key', 'Hello, world!') </script> <template> <div> <input> </div> </template>
第一次加载时, input
显示 'Hello, world!',但最后,它会显示你最后在 input
中输入的内容,因为它被保存在localstorage中。
除了 localstorage,我们也可以指定 sessionstorage
:
const input = useStorage('unique-key', 'Hello, world!', sessionStorage)
当然,也可以自己实现存储系统,只要它实现了StorageLike
接口。
export interface StorageLike { getItem(key: string): string | null setItem(key: string, value: string): void removeItem(key: string): void }
5、useVModel
v-model
指令是很好的语法糖,使双向数据绑定更容易。
但useVModel
更进一步,摆脱了一堆没有人真正想写的模板代码。
<script> import { useVModel } from '@vueuse/core' const props = defineProps({ count: Number, }) const emit = defineEmits(['update:count']) const count = useVModel(props, 'count', emit) </script> <template> <div> <button>-</button> <button>Reset to 0</button> <button>+</button> </div> </template>
在这个例子中,我们首先定义了要附加到v-model
上的 props:
const props = defineProps({ count: Number, })
然后我们发出一个事件,使用v-model
的命名惯例update:<propname></propname>
:
const emit = defineEmits(['update:count'])
现在,我们可以使用useVModel
组合来将 prop
和事件绑定到一个ref
。
const count = useVModel(props, 'count', emit)
每当 prop 发生变化时,这个 count
就会改变。但只要它从这个组件中被改变,它就会发出update:count
事件,通过v-model
指令触发更新。
我们可以像这样使用这个 Input
组件。
<script> import { ref } from 'vue' import Input from './components/Input.vue' const count = ref(50) </script> <template> <div> <input> {{ count }} </div> </template>
这里的count ref
是通过v-model
绑定与 Input
组件内部的count ref
同步的。
事例地址:https://stackblitz.com/edit/vue3-script-setup-with-vite-ut5ap8?file=src%2FApp.vue
6、useImage
随着时间的推移,web应用中的图像变得越来越漂亮。我们已经有了带有srcset
的响应式图像,渐进式加载库,以及只有在图像滚动到视口时才会加载的库。
但你知道吗,我们也可以访问图像本身的加载和错误状态?
我以前主要通过监听每个HTML元素发出的onload
和onerror
事件来做到这一点,但VueUse给我们提供了一个更简单的方法,那就是useImage
组合。
<script> import { useImage } from '@vueuse/core' // Change this to a non-existent URL to see the error state const url = 'https://source.unsplash.com/random/400x300' const { isLoading, error } = useImage( { src: url, }, { // Just to show the loading effect more clearly delay: 2000, } ) </script> <template> <div> <div></div> <div>Couldn't load the image :(</div> <img src="/static/imghwm/default1.png" data-src="url" class="lazy" alt="總結分享幾個 VueUse 最佳組合,快來收藏使用吧!" > </div> </template>
第一步,通过useImage
设置图片的src
:
const { isLoading, error } = useImage({ src: url })
获取它返回的isLoading
和error
引用,以便跟踪状态。这个组合在内部使用useAsyncState
,因此它返回的值与该组合的值相同。
安排好后,useImage
就会加载我们的图像并将事件处理程序附加到它上面。
我们所要做的就是在我们的模板中使用相同的URL来使用该图片。由于浏览器会重复使用任何缓存的图片,它将重复使用由useImage
加载的图片。
<template> <div> <div></div> <div>Couldn't load the image :(</div> <img src="/static/imghwm/default1.png" data-src="url" class="lazy" alt="總結分享幾個 VueUse 最佳組合,快來收藏使用吧!" > </div> </template>
在这里,我们设置了一个基本的加载和错误状态处理程序。当图片正在加载时,我们显示一个带有动画渐变的占位符。如果有错误,我们显示一个错误信息。否则我们可以渲染图像。
UseImage 还有其他一些很棒的特性!如果想让它成为响应式图像,那么它支持srcset
和sizes
属性,这些属性在幕后传递给img
元素。
如果你想把所有内容都放在模板中,还有一个无渲染组件。它的工作原理与组合的相同:
<template> <useimage> <template> <div></div> </template> <template> Oops! </template> </useimage> </template>
事例:https://stackblitz.com/edit/vue3-script-setup-with-vite-d1jsec?file=src%2FApp.vue
7、暗黑模式 useDark
最近,每个网站和应用程序似乎都有暗黑模式。最难的部分是造型的改变。但是一旦你有了这些,来回切换就很简单了。
如果你使用的是Tailwind,你只需要在html元素中添加dark类,就可以在整个页面中启用。
<!-- ... -->
然而,在黑暗模式和光明模式之间切换时,有几件事需要考虑。首先,我们要考虑到用户的系统设置。第二,我们要记住他们是否已经推翻了这个选择。
VueUse的useDark
组合性为我们把所有这些东西都包起来。默认情况下,它查看系统设置,但任何变化都会被持久化到localStorage
,所以设置会被记住。
<script> import { useDark, useToggle } from '@vueuse/core' const isDark = useDark() const toggleDark = useToggle(isDark) </script> <template> <div> Changes with dark/light mode. <button> Enable {{ isDark ? 'Light' : 'Dark' }} Mode </button> </div> </template>
黑暗模式的样式:
.dark .container { background: slategrey; color: white; border-color: black; } .dark button { background: lightgrey; color: black; } .dark body { background: darkgrey; }
如果你没有使用Tailwind,你可以通过传入一个选项对象来完全定制黑暗模式的应用方式。下面是默认的Tailwind:
const isDark = useDark({ selector: 'html', attribute: 'class', valueDark: 'dark', valueLight: '', })
也可以提供一个onChanged处理程序,这样你就可以编写任何你需要的Javascript。这两种方法使你可以使它与你已有的任何造型系统一起工作。
總結
Vueuse 擁有一個巨大的函式庫,其中包含出色的組合,而我們在這裡只涵蓋了其中的一小部分。我強烈建議你花些時間去探索這些文檔,看看所有可用的東西。這是一個非常好的資源,它將使你免於大量的模板程式碼和不斷地重新發明車輪。
以上是總結分享幾個 VueUse 最佳組合,快來收藏使用吧!的詳細內容。更多資訊請關注PHP中文網其他相關文章!

NetflixusesAcustomFrameworkcalled“ Gibbon” BuiltonReact,notReactorVuedIrectly.1)TeamSperience:selectBasedonFamiliarity.2)ProjectComplexity:vueforsimplerprojects:reactforforforproproject,reactforforforcompleplexones.3)cocatizationneedneeds:reactoffipicatizationneedneedneedneedneedneeds:reactoffersizationneedneedneedneedneeds:reactoffersizatization needefersmoreflexibleise.4)

Netflix在框架選擇上主要考慮性能、可擴展性、開發效率、生態系統、技術債務和維護成本。 1.性能與可擴展性:選擇Java和SpringBoot以高效處理海量數據和高並發請求。 2.開發效率與生態系統:使用React提升前端開發效率,利用其豐富的生態系統。 3.技術債務與維護成本:選擇Node.js構建微服務,降低維護成本和技術債務。

Netflix主要使用React作為前端框架,輔以Vue用於特定功能。 1)React的組件化和虛擬DOM提升了Netflix應用的性能和開發效率。 2)Vue在Netflix的內部工具和小型項目中應用,其靈活性和易用性是關鍵。

Vue.js是一種漸進式JavaScript框架,適用於構建複雜的用戶界面。 1)其核心概念包括響應式數據、組件化和虛擬DOM。 2)實際應用中,可以通過構建Todo應用和集成VueRouter來展示其功能。 3)調試時,建議使用VueDevtools和console.log。 4)性能優化可通過v-if/v-show、列表渲染優化和異步加載組件等實現。

Vue.js適合小型到中型項目,而React更適用於大型、複雜應用。 1.Vue.js的響應式系統通過依賴追踪自動更新DOM,易於管理數據變化。 2.React採用單向數據流,數據從父組件流向子組件,提供明確的數據流向和易於調試的結構。

Vue.js適合中小型項目和快速迭代,React適用於大型複雜應用。 1)Vue.js易於上手,適用於團隊經驗不足或項目規模較小的情況。 2)React的生態系統更豐富,適合有高性能需求和復雜功能需求的項目。

實現 Vue 中 a 標籤跳轉的方法包括:HTML 模板中使用 a 標籤指定 href 屬性。使用 Vue 路由的 router-link 組件。使用 JavaScript 的 this.$router.push() 方法。可通過 query 參數傳遞參數,並在 router 選項中配置路由以進行動態跳轉。

Vue 中實現組件跳轉有以下方法:使用 router-link 和 <router-view> 組件進行超鏈接跳轉,指定 :to 屬性為目標路徑。直接使用 <router-view> 組件顯示當前路由渲染的組件。使用 router.push() 和 router.replace() 方法進行程序化導航,前者保存歷史記錄,後者替換當前路由不留記錄。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Dreamweaver CS6
視覺化網頁開發工具

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。