目錄
1、keepalive功能
2、keepalive使用場景
3、在專案中的使用過程
4、vue3 keepalive原始碼偵錯
5、vue3 keealive原始碼粗淺分析
首頁 web前端 Vue.js vue3 keepalive線上問題怎麼解決

vue3 keepalive線上問題怎麼解決

May 19, 2023 am 08:04 AM
vue3 keepalive

1、keepalive功能

  • keepalive是vue3中的一個全域元件

  • keepalive 本身不會渲染出來,也不會出現在dom節點當中,但是它會被渲染為vnode,透過vnode可以追蹤到keepalive中的cache和keys,當然也是在開發環境才可以,build打包以後沒有暴露到vnode中(這個還要再確認一下)

  • keepalive 最重要的功能就是快取元件

  • #keepalive 透過LRU快取淘汰策略來更新元件緩存,可以更有效的利用內存,防止記憶體溢出,原始碼中的最大快取數max為10,也就是10個元件之後,就開始淘汰最先被快取的元件了

2、keepalive使用場景

  • 這裡先假設一個場景: A頁面是首頁=====> B頁面清單頁面(需要快取的頁面)=======> C 詳情頁由C詳情頁到到B頁面的時候,要回到B的快取頁面,包括頁面的基礎資料和清單的捲軸位置資訊如果由B頁面返回到A頁面,則需要將B的快取頁清空

  • 上述另一個場景:進入頁面直接緩存,然後就結束了,這個比較簡單本文就不討論了

3、在專案中的使用過程

vue3 keepalive線上問題怎麼解決

keepalive元件總共有三個參數

  • #include:可傳字串、正規表示式、數組,名稱匹配成功的元件會被快取

  • exclude:可傳字串、正規表示式、數組,名稱符合成功的元件不會被快取

  • max:可傳數字,限制快取元件的最大數量,預設為10

#首先在App.vue根程式碼中加入引入keepalive元件,透過這裡可以發現,我在這裡快取的相當於整個頁面,當然你也可以進行更細緻的控制頁面當中的某個區域元件

    <template>
        <router-view v-slot="{ Component }">
            <keep-alive :include="keepAliveCache">
                <component :is="Component" :key="$route.name" />
            </keep-alive>
        </router-view>
    </template>
    <script lang="ts" setup>
    import { computed } from "vue";
    import { useKeepAliverStore } from "@/store";
    const useStore = useKeepAliverStore();
    const keepAliveCache = computed(() => {
        return useStore.caches;
    });
    </script>
登入後複製

透過App.vue可以發現,透過pinia(也就是vue2中使用的vuex)來保存要快取的頁面元件, 來處理include緩存,和保存頁面元件中的滾動條資訊資料

    import { defineStore } from "pinia";
    export const useKeepAliverStore = defineStore("useKeepAliverStore", {
        state: () => ({
            caches: [] as any,
            scrollList: new Map(),  // 缓存页面组件如果又滚动条的高度
        }),
        actions: {
            add(name: string) {
                this.caches.push(name);
            },
            remove(name: string) {
                console.log(this.caches, &#39;this.caches&#39;)
                this.caches = this.caches.filter((item: any) => item !== name);
                console.log(this.caches, &#39;this.caches&#39;)
            },
            clear() {
                this.caches = []
            }
        }
    });
登入後複製

元件路由剛切換時,透過beforeRouteEnter將元件寫入include, 此時元件生命週期還沒開始。如果都已經開始執行元件生命週期了,再寫入就意義了。

所以這個鉤子函數就不能寫在setup中,要單獨提出來寫。當然你也可以換成路由的其他鉤子函數處理beforeEach,但這裡面使用的話,好像使用不了pinia,這個還需要進一步研究一下。

    import { useRoute, useRouter, onBeforeRouteLeave } from "vue-router";
    import { useKeepAliverStore } from "@/store";
    const useStore = useKeepAliverStore()
    export default {
        name:"record-month",
        beforeRouteEnter(to, from, next) {
            next(vm => {
                if(from.name === &#39;Home&#39; && to.name === &#39;record-month&#39;) {
                useStore.add(to.name)
                }
            });
        }
    }
    </script>
登入後複製

元件路由離開時判斷,是否要移出緩存,這個鉤子就直接寫在setup裡就可以了。

    onBeforeRouteLeave((to, from) => {
        console.log(to.name, "onBeforeRouteLeave");
        if (to.name === "new-detection-detail") {
            console.log(to, from, "进入详情页面不做处理");
        } else {
            useStore.remove(from.name)
            console.log(to, from, "删除组件缓存");
        }
    });
登入後複製

在keepalive兩個鉤子函數中進行處理scroll位置的快取,onActivated中取得快取中的位置, onDeactivated記錄位置到快取

    onActivated(() => {
        if(useStore.scrollList.get(routeName)) {
            const top = useStore.scrollList.get(routeName)
            refList.value.setScrollTop(Number(top))
        }
    });
    onDeactivated(() => {
        const top = refList.value.getScrollTop()
        useStore.scrollList.set(routeName, top)
    });
登入後複製

這裡定義一個方法,設定scrollTop使用了原生javascript的api

    const setScrollTop = (value: any) => {
        const dom = document.querySelector(&#39;.van-pull-refresh&#39;)
        dom!.scrollTop = value
    }
登入後複製

同時高度怎麼取得要先註冊scroll事件,然後透過getScrollTop 取得目前捲軸的位置進行儲存即可

    onMounted(() => {
        scrollDom.value = document.querySelector(&#39;.van-pull-refresh&#39;) as HTMLElement
        const throttledFun = useThrottleFn(() => {
            console.log(scrollDom.value?.scrollTop, &#39;addEventListener&#39;)
            state.scrollTop = scrollDom.value!.scrollTop
        }, 500)
        if(scrollDom.value) {
            scrollDom.value.addEventListener(&#39;scroll&#39;,throttledFun)
        }
    })
    const getScrollTop = () => {
        console.log(&#39;scrollDom.vaue&#39;, scrollDom.value?.scrollTop)
        return state.scrollTop
    }
登入後複製

上面註冊scroll事件中使用了一個useThrottleFn ,這個類別庫是@vueuse/core中提供的,其中封裝了很多工具都非常不錯,用興趣的可以研究研究

    https://vueuse.org/shared/usethrottlefn/#usethrottlefn
登入後複製

此時也可以查看找到實例的vnode查找到keepalive,是在keepalive緊鄰的子元件裡

    const instance = getCurrentInstance()
    console.log(instance.vnode.parent) // 这里便是keepalive组件vnode
    // 如果是在开发环境中可以查看到cache对象
    instance.vnode.parent.__v_cache
    // vue源码中,在dev环境对cache进行暴露,生产环境是看不到的
    if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) {
        ;(instance as any).__v_cache = cache
    }
登入後複製

4、vue3 keepalive原始碼偵錯

1、複製程式碼

    git clone git@github.com:vuejs/core.git
登入後複製

2、安裝相依

    pnpm i
登入後複製

3 、如果無法使用pnpm,可以先透過npm安裝一下

    npm i pnpm -g
登入後複製

4、安裝完成以後,找到根目錄package.json檔案中的scripts

    // 在dev命令后添加 --source-map是从已转换的代码,映射到原始的源文件
    "dev": "node scripts/dev.js  --sourcemap"
登入後複製

參考 https://www.yisu .com/article/154583.htm

5、執行pnpm run dev則會build vue原始碼

    pnpm run dev
    //则会出现以下,代表成功了(2022年5月27日),后期vue源代码作者可能会更新,相应的提示可能发生变更,请注意一下
    > @3.2.36 dev H:\github\sourceCode\core
    > node scripts/dev.js  --sourcemap
    watching: packages\vue\dist\vue.global.js
    //到..\..\core\packages\vue\dist便可以看到编译成功,以及可以查看到examples样例demo页面
登入後複製

6、然後在....\core\packages\vue\examples\composition中加入一個aehyok.html文件,將如下程式碼進行拷貝,然後透過chrome瀏覽器打開,F12,找到原始碼的Tab頁面,透過快捷鍵Ctrl P 輸入KeepAlive便可以找到這個元件,然後透過左側行標右鍵就可以加入斷點,進行調試,也可以透過右側的【呼叫堆疊】進行快速跳轉程式碼進行調試。

    <script src="../../dist/vue.global.js"></script>
    <script type="text/x-template" id="template-1">
        <div>template-1</div>
        <div>template-1</div>
    </script>
    <script type="text/x-template" id="template-2">
        <div>template-2</div>
        <div>template-2</div>
    </script>
    <script>
    const { reactive, computed } = Vue
    const Demo1 = {
        name: &#39;Demo1&#39;,
        template: &#39;#template-1&#39;,
        setup(props) {
        }
    }
    const Demo2 = {
        name: &#39;Demo2&#39;,
        template: &#39;#template-2&#39;,
        setup(props) {
        }
    }
    </script>
    <!-- App template (in DOM) -->
    <div id="demo">
        <div>Hello World</div>
        <div>Hello World</div>
        <div>Hello World</div>
        <button @click="changeClick(1)">组件一</button>
        <button @click="changeClick(2)">组件二</button>
        <keep-alive :include="includeCache">
            <component :is="componentCache" :key="componentName" v-if="componentName" />
        </keep-alive>
    </div>
    <!-- App script -->
    <script>
    Vue.createApp({
    components: {
        Demo1,
        Demo2
    },
    data: () => ({
        includeCache: [],
        componentCache: &#39;&#39;,
        componentName: &#39;&#39;,
    }),
    methods:{
        changeClick(type) {
            if(type === 1) {
                if(!this.includeCache.includes(&#39;Demo1&#39;)) {
                    this.includeCache.push(&#39;Demo1&#39;)
                }
                console.log(this.includeCache, &#39;000&#39;)
                this.componentCache = Demo1
                this.componentName = &#39;Demo1&#39;
            }
            if(type === 2) {
                if(!this.includeCache.includes(&#39;Demo2&#39;)) {
                    this.includeCache.push(&#39;Demo2&#39;)
                }
                console.log(this.includeCache, &#39;2222&#39;)
                this.componentName = &#39;Demo2&#39;
                this.componentCache = Demo2
            }
        }
    }
    }).mount(&#39;#demo&#39;)
    </script>
登入後複製

7、偵錯原始碼發現keepalive中的render函數(或說時setup中的return 函數)在子元件切換時就會去執行,變更邏輯快取

  • #第一次進入頁面初始化keepalive元件會執行一次,

  • 然後點選元件一,再執行render函數

  • 然後點選元件二,會再執行render函數

8、偵錯截圖說明

vue3 keepalive線上問題怎麼解決

5、vue3 keealive原始碼粗淺分析

透過查看vue3 KeepAlive.ts原始碼

    // 在setup初始化中,先获取keepalive实例
    // getCurrentInstance() 可以获取当前组件的实例
    const instance = getCurrentInstance()!
    // KeepAlive communicates with the instantiated renderer via the
    // ctx where the renderer passes in its internals,
    // and the KeepAlive instance exposes activate/deactivate implementations.
    // The whole point of this is to avoid importing KeepAlive directly in the
    // renderer to facilitate tree-shaking.
    const sharedContext = instance.ctx as KeepAliveContext
    // if the internal renderer is not registered, it indicates that this is server-side rendering,
    // for KeepAlive, we just need to render its children
    /// SSR 判断,暂时可以忽略掉即可。
    if (__SSR__ && !sharedContext.renderer) {
        return () => {
            const children = slots.default && slots.default()
            return children && children.length === 1 ? children[0] : children
        }
    }
    // 通过Map存储缓存vnode,
    // 通过Set存储缓存的key(在外面设置的key,或者vnode的type)
    const cache: Cache = new Map()
    const keys: Keys = new Set()
    let current: VNode | null = null
    if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) {
    ;(instance as any).__v_cache = cache
    }
    const parentSuspense = instance.suspense
    const {
    renderer: {
        p: patch,
        m: move,
        um: _unmount,
        o: { createElement }
    }
    } = sharedContext
    // 创建了隐藏容器
    const storageContainer = createElement(&#39;div&#39;)
    // 在实例上注册两个钩子函数 activate,  deactivate
    sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => {
        const instance = vnode.component!
        move(vnode, container, anchor, MoveType.ENTER, parentSuspense)
        // in case props have changed
        patch(
            instance.vnode,
            vnode,
            container,
            anchor,
            instance,
            parentSuspense,
            isSVG,
            vnode.slotScopeIds,
            optimized
        )
        queuePostRenderEffect(() => {
            instance.isDeactivated = false
            if (instance.a) {
            invokeArrayFns(instance.a)
            }
            const vnodeHook = vnode.props && vnode.props.onVnodeMounted
            if (vnodeHook) {
            invokeVNodeHook(vnodeHook, instance.parent, vnode)
            }
        }, parentSuspense)
        if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) {
            // Update components tree
            devtoolsComponentAdded(instance)
        }
    }
    sharedContext.deactivate = (vnode: VNode) => {
        const instance = vnode.component!
        move(vnode, storageContainer, null, MoveType.LEAVE, parentSuspense)
        queuePostRenderEffect(() => {
            if (instance.da) {
            invokeArrayFns(instance.da)
            }
            const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted
            if (vnodeHook) {
            invokeVNodeHook(vnodeHook, instance.parent, vnode)
            }
            instance.isDeactivated = true
        }, parentSuspense)
        if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) {
            // Update components tree
            devtoolsComponentAdded(instance)
        }
    }
    // 组件卸载
    function unmount(vnode: VNode) {
        // reset the shapeFlag so it can be properly unmounted
        resetShapeFlag(vnode)
        _unmount(vnode, instance, parentSuspense, true)
    }
    // 定义 include和exclude变化时,对缓存进行动态处理
    function pruneCache(filter?: (name: string) => boolean) {
        cache.forEach((vnode, key) => {
            const name = getComponentName(vnode.type as ConcreteComponent)
            if (name && (!filter || !filter(name))) {
            pruneCacheEntry(key)
            }
        })
    }
    function pruneCacheEntry(key: CacheKey) {
        const cached = cache.get(key) as VNode
        if (!current || cached.type !== current.type) {
            unmount(cached)
        } else if (current) {
            // current active instance should no longer be kept-alive.
            // we can&#39;t unmount it now but it might be later, so reset its flag now.
            resetShapeFlag(current)
        }
        cache.delete(key)
        keys.delete(key)
    }
    // 可以发现通过include 可以配置被显示的组件,
    // 当然也可以设置exclude来配置不被显示的组件,
    // 组件切换时随时控制缓存
    watch(
    () => [props.include, props.exclude],
    ([include, exclude]) => {
        include && pruneCache(name => matches(include, name))
        exclude && pruneCache(name => !matches(exclude, name))
    },
    // prune post-render after `current` has been updated
    { flush: &#39;post&#39;, deep: true }
    )
    // 定义当前组件Key
    // cache sub tree after render
        let pendingCacheKey: CacheKey | null = null
        // 这是一个重要的方法,设置缓存
        const cacheSubtree = () => {
        // fix #1621, the pendingCacheKey could be 0
        if (pendingCacheKey != null) {
            cache.set(pendingCacheKey, getInnerChild(instance.subTree))
        }
        }
        onMounted(cacheSubtree)
        onUpdated(cacheSubtree)
        // 组件卸载的时候,对缓存列表进行循环判断处理
        onBeforeUnmount(() => {
            cache.forEach(cached => {
                const { subTree, suspense } = instance
                const vnode = getInnerChild(subTree)
                if (cached.type === vnode.type) {
                // current instance will be unmounted as part of keep-alive&#39;s unmount
                resetShapeFlag(vnode)
                // but invoke its deactivated hook here
                const da = vnode.component!.da
                da && queuePostRenderEffect(da, suspense)
                return
                }
                unmount(cached)
            })
        })
    // 同时在keepAlive组件setup生命周期中,return () => {} 渲染的时候,对组件进行判断逻辑处理,同样对include和exclude判断渲染。
    // 判断keepalive组件中的子组件,如果大于1个的话,直接警告处理了
    // 另外如果渲染的不是虚拟dom(vNode),则直接返回渲染即可。
    return () => {
        // eslint-disable-next-line no-debugger
        console.log(props.include, &#39;watch-include&#39;)
        pendingCacheKey = null
        if (!slots.default) {
            return null
        }
        const children = slots.default()
        const rawVNode = children[0]
        if (children.length > 1) {
            if (__DEV__) {
            warn(`KeepAlive should contain exactly one component child.`)
            }
            current = null
            return children
        } else if (
            !isVNode(rawVNode) ||
            (!(rawVNode.shapeFlag & ShapeFlags.STATEFUL_COMPONENT) &&
            !(rawVNode.shapeFlag & ShapeFlags.SUSPENSE))
        ) {
            current = null
            return rawVNode
        }
        // 接下来处理时Vnode虚拟dom的情况,先获取vnode
        let vnode = getInnerChild(rawVNode)
        // 节点类型
        const comp = vnode.type as ConcreteComponent
        // for async components, name check should be based in its loaded
        // inner component if available
        // 获取组件名称
        const name = getComponentName(
            isAsyncWrapper(vnode)
            ? (vnode.type as ComponentOptions).__asyncResolved || {}
            : comp
        )
        //这个算是最熟悉的通过props传递进行的参数,进行解构
        const { include, exclude, max } = props
        // include判断 组件名称如果没有设置, 或者组件名称不在include中,
        // exclude判断 组件名称有了,或者匹配了
        // 对以上两种情况都不进行缓存处理,直接返回当前vnode虚拟dom即可。
        if (
            (include && (!name || !matches(include, name))) ||
            (exclude && name && matches(exclude, name))
        ) {
            current = vnode
            return rawVNode
        }
        // 接下来开始处理有缓存或者要缓存的了
        // 先获取一下vnode的key设置,然后看看cache缓存中是否存在
        const key = vnode.key == null ? comp : vnode.key
        const cachedVNode = cache.get(key)
        // 这一段可以忽略了,好像时ssContent相关,暂时不管了,没看明白??
        // clone vnode if it&#39;s reused because we are going to mutate it
        if (vnode.el) {
            vnode = cloneVNode(vnode)
            if (rawVNode.shapeFlag & ShapeFlags.SUSPENSE) {
            rawVNode.ssContent = vnode
            }
        }
        // 上面判断了,如果没有设置key,则使用vNode的type作为key值
        pendingCacheKey = key
        //判断上面缓存中是否存在vNode
        // if 存在的话,就将缓存中的vnode复制给当前的vnode
        // 同时还判断了组件是否为过渡组件 transition,如果是的话 需要注册过渡组件的钩子
        // 同时先删除key,然后再重新添加key
        // else 不存在的话,就添加到缓存即可
        // 并且要判断一下max最大缓存的数量是否超过了,超过了,则通过淘汰LPR算法,删除最旧的一个缓存
        // 最后又判断了一下是否为Suspense。也是vue3新增的高阶组件。
        if (cachedVNode) {
            // copy over mounted state
            vnode.el = cachedVNode.el
            vnode.component = cachedVNode.component
            if (vnode.transition) {
            // recursively update transition hooks on subTree
            setTransitionHooks(vnode, vnode.transition!)
            }
            // avoid vnode being mounted as fresh
            vnode.shapeFlag |= ShapeFlags.COMPONENT_KEPT_ALIVE
            // make this key the freshest
            keys.delete(key)
            keys.add(key)
        } else {
            keys.add(key)
            // prune oldest entry
            if (max && keys.size > parseInt(max as string, 10)) {
            pruneCacheEntry(keys.values().next().value)
            }
        }
        // avoid vnode being unmounted
        vnode.shapeFlag |= ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE
        current = vnode
        return isSuspense(rawVNode.type) ? rawVNode : vnode
登入後複製

以上是vue3 keepalive線上問題怎麼解決的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1664
14
CakePHP 教程
1423
52
Laravel 教程
1319
25
PHP教程
1269
29
C# 教程
1248
24
Vue3如何實作刷新頁面局部內容 Vue3如何實作刷新頁面局部內容 May 26, 2023 pm 05:31 PM

想要實現頁面的局部刷新,我們只需要實現局部元件(dom)的重新渲染。在Vue中,想要實現這效果最簡單的方式方法就是使用v-if指令。在Vue2中我們除了使用v-if指令讓局部dom的重新渲染,也可以新建一個空白元件,需要刷新局部頁面時跳轉至這個空白元件頁面,然後在空白元件內的beforeRouteEnter守衛中又跳轉回原來的頁面。如下圖所示,如何在Vue3.X中實現點擊刷新按鈕實現紅框範圍內的dom重新加載,並展示對應的加載狀態。由於Vue3.X中scriptsetup語法中組件內守衛只有o

vue3專案中怎麼使用tinymce vue3專案中怎麼使用tinymce May 19, 2023 pm 08:40 PM

tinymce是一個功能齊全的富文本編輯器插件,但在vue中引入tinymce並不像別的Vue富文本插件一樣那麼順利,tinymce本身並不適配Vue,還需要引入@tinymce/tinymce-vue,並且它是國外的富文本插件,沒有透過中文版本,需要在其官網下載翻譯包(可能需要翻牆)。 1.安裝相關依賴npminstalltinymce-Snpminstall@tinymce/tinymce-vue-S2、下載中文包3.引入皮膚和漢化包在項目public資料夾下新建tinymce資料夾,將下載的

vue3+vite:src使用require動態匯入圖片報錯怎麼解決 vue3+vite:src使用require動態匯入圖片報錯怎麼解決 May 21, 2023 pm 03:16 PM

vue3+vite:src使用require動態導入圖片報錯和解決方法vue3+vite動態的導入多張圖片vue3如果使用的是typescript開發,就會出現require引入圖片報錯,requireisnotdefined不能像使用vue2這樣imgUrl:require(' …/assets/test.png')導入,是因為typescript不支援require所以用import導入,下面介紹如何解決:使用awaitimport

Vue3怎麼解析markdown並實現程式碼高亮顯示 Vue3怎麼解析markdown並實現程式碼高亮顯示 May 20, 2023 pm 04:16 PM

Vue實作部落格前端,需要實作markdown的解析,如果有程式碼則需要實作程式碼的高亮。 Vue的markdown解析函式庫很多,如markdown-it、vue-markdown-loader、marked、vue-markdown等。這些庫都大同小異。這裡選用的是marked,程式碼高亮的函式庫選用的是highlight.js。具體實現步驟如下:一、安裝依賴庫在vue專案下開啟命令窗口,並輸入以下命令npminstallmarked-save//marked用於將markdown轉換成htmlnpmins

Vue3中怎麼實現選取頭像並裁剪 Vue3中怎麼實現選取頭像並裁剪 May 29, 2023 am 10:22 AM

最終效果安裝VueCropper組件yarnaddvue-cropper@next上面的安裝值針對Vue3的,如果時Vue2或想使用其他的方式引用,請訪問它的npm官方地址:官方教程。在元件中引用使用時也很簡單,只需要引入對應的元件和它的樣式文件,我這裡沒有在全域引用,只在我的元件檔案中引入import{userInfoByRequest}from'../js/api' import{VueCropper}from'vue-cropper&

Vue3復用元件怎麼使用 Vue3復用元件怎麼使用 May 20, 2023 pm 07:25 PM

前言無論是vue還是react,當我們遇到多處重複程式碼的時候,我們都會想著如何重複使用這些程式碼,而不是一個檔案裡充斥著一堆冗餘程式碼。實際上,vue和react都可以透過抽組件的方式來達到復用,但如果遇到一些很小的程式碼片段,你又不想抽到另外一個檔案的情況下,相比而言,react可以在相同文件裡面宣告對應的小元件,或透過renderfunction來實現,如:constDemo:FC=({msg})=>{returndemomsgis{msg}}constApp:FC=()=>{return(

怎麼使用vue3+ts+axios+pinia實現無感刷新 怎麼使用vue3+ts+axios+pinia實現無感刷新 May 25, 2023 pm 03:37 PM

vue3+ts+axios+pinia實作無感刷新1.先在專案中下載aiXos和pinianpmipinia--savenpminstallaxios--save2.封裝axios請求-----下載js-cookienpmiJS-cookie-s//引入aixosimporttype{AxiosRequestConfigig ,AxiosResponse}from"axios";importaxiosfrom'axios';import{ElMess

vue3怎麼使用vueup/vue-quill富文本並限制輸入字數 vue3怎麼使用vueup/vue-quill富文本並限制輸入字數 May 20, 2023 pm 04:16 PM

一、效果展示二、npmnpminstall@vueup/vue-quill@alpha--save三、main.js引入import{QuillEditor}from'@vueup/vue-quill'import'@vueup/vue-quill/dist/vue- quill.snow.css';app.component('QuillEditor',QuillEditor)四、頁面使用{{TiLe

See all articles