1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        Vue3新玩具,讓你寫出更好的vue3代碼

        共 2955字,需瀏覽 6分鐘

         ·

        2021-11-22 23:05

        前言

        鬼哥推薦大家,想更好寫出優(yōu)秀vue3代碼的,記得一定要看看

        尤大大在一次直播中提到了 VueUse 的一個庫。好奇了一下,點看看了看。好家伙啊, 我直接好家伙。這不就是曾經(jīng)我也想自己寫一個 vue 版的 hooks 庫嗎?(因為我覺得 vue3hooks 太像了) 可是我還不太會, 你現(xiàn)在直接把我的夢想給破滅了,下面我們一起來看看吧!

        什么是 VueUse

        VueUse 是一個基于 Composition API 的實用函數(shù)集合。通俗的來說,這就是一個工具函數(shù)包,它可以幫助你快速實現(xiàn)一些常見的功能,免得你自己去寫,解決重復(fù)的工作內(nèi)容。以及進(jìn)行了基于 Composition API 的封裝。讓你在 vue3 中更加得心應(yīng)手。

        簡單上手

        安裝 VueUse

        npm?i?@vueuse/core

        使用 VueUse

        //?導(dǎo)入
        import?{?useMouse,?usePreferredDark,?useLocalStorage?}?from?'@vueuse/core'

        export?default?{
        ??setup()?{
        ????//?tracks?mouse?position
        ????const?{?x,?y?}?=?useMouse()

        ????//?is?user?prefers?dark?theme
        ????const?isDark?=?usePreferredDark()

        ????//?persist?state?in?localStorage
        ????const?store?=?useLocalStorage(
        ??????'my-storage',
        ??????{
        ????????name:?'Apple',
        ????????color:?'red',
        ??????},
        ????)

        ????return?{?x,?y,?isDark,?store?}
        ??}
        }

        上面從 VueUse 當(dāng)中導(dǎo)入了三個函數(shù), useMouse, usePreferredDark, useLocalStorage。useMouse 是一個監(jiān)聽當(dāng)前鼠標(biāo)坐標(biāo)的一個方法,他會實時的獲取鼠標(biāo)的當(dāng)前的位置。usePreferredDark 是一個判斷用戶是否喜歡深色的方法,他會實時的判斷用戶是否喜歡深色的主題。useLocalStorage 是一個用來持久化數(shù)據(jù)的方法,他會把數(shù)據(jù)持久化到本地存儲中。

        還有我們熟悉的 防抖節(jié)流

        import?{?throttleFilter,?debounceFilter,?useLocalStorage,?useMouse?}?from?'@vueuse/core'

        //?以節(jié)流的方式去改變?localStorage?的值
        const?storage?=?useLocalStorage('my-key',?{?foo:?'bar'?},?{?eventFilter:?throttleFilter(1000)?})

        //?100ms后更新鼠標(biāo)的位置
        const?{?x,?y?}?=?useMouse({?eventFilter:?debounceFilter(100)?})

        還有還有在 component 中使用的函數(shù)


        import?{?ref?}?from?'vue'
        import?{?onClickOutside?}?from?'@vueuse/core'

        const?el?=?ref()

        function?close?()?{
        ??/*?...?*/
        }

        onClickOutside(el,?close)
        </script>