使用?Vue3?實(shí)現(xiàn)文章目錄功能
前言
這一段時(shí)間一直在做一個(gè)博客項(xiàng)目 Kila Kila Blog,找了一圈發(fā)現(xiàn)沒有特別滿足自己需求的目錄組件,所以決定自己動手,完成一個(gè)滿足以下預(yù)期目標(biāo)的目錄組件:
- 自動高亮選中當(dāng)前正在閱讀的章節(jié)
- 自動展開當(dāng)前正在閱讀的章節(jié)的子標(biāo)題,并隱藏其他章節(jié)的子標(biāo)題
- 顯示閱讀進(jìn)度
完成后的目錄組件如下圖左側(cè)所示:
實(shí)現(xiàn)過程
由于標(biāo)題之間有父子的關(guān)系,所以我們應(yīng)該用樹數(shù)據(jù)結(jié)構(gòu)來解決這個(gè)問題。我們遍歷文章容器中的所有標(biāo)簽,如果遇到 <h1>
、<h2>
這類標(biāo)簽,就創(chuàng)建一個(gè)節(jié)點(diǎn),將其放到列表中,之后使用 v-for
指令來生成目錄就行了。下面分析一下每個(gè)節(jié)點(diǎn)需要有哪些屬性。
一個(gè)樹的節(jié)點(diǎn),應(yīng)該具有的屬性包括:父節(jié)點(diǎn)的指針 parent
、子節(jié)點(diǎn)的指針列表 children
,因?yàn)橐粋€(gè)節(jié)點(diǎn)代表一個(gè)標(biāo)題,所以還要包含:標(biāo)題的 ID號 id
(用于 v-for
的 key
),標(biāo)題名 name
(添加了標(biāo)題的序號)、原始標(biāo)題名 rawName
和標(biāo)題的可見性 isVisible
,當(dāng)我們點(diǎn)擊標(biāo)題時(shí),應(yīng)該滾動到標(biāo)題的位置,所以還要有 scrollTop
屬性。在我們遍歷文章容器中的所有標(biāo)簽時(shí),需要判斷當(dāng)前遇到的標(biāo)簽和上一個(gè)標(biāo)簽之間的父子關(guān)系,所以要有一個(gè) level
屬性代表每一個(gè)節(jié)點(diǎn)的等級。下面是具體實(shí)現(xiàn)代碼:
<template> <div class="catalog-card" v-if="Object.keys(titles).length > 0"> <div class="catalog-card-header"> <div> <span ><font-awesome-icon :icon="['fas', 'bars-staggered']" class="catalog-icon" /></span> <span>目錄</span> </div> <span class="progress">{{ progress }}</span> </div> <div class="catalog-content"> <div v-for="title in titles" :key="title.id" @click="scrollToView(title.scrollTop)" :class="[ 'catalog-item', currentTitle.id == title.id ? 'active' : 'not-active', ]" :style="{ marginLeft: title.level * 20 + 'px' }" v-show="title.isVisible" :title="title.rawName" > {{ title.name }} </div> </div> </div> </template> <script> import { reactive, ref } from "vue"; export default { name: "KilaKilaCatalog", setup(props) { let titles = reactive(getTitles()); let currentTitle = reactive({}); let progress = ref(0); // 獲取目錄的標(biāo)題 function getTitles() { let titles = []; let levels = ["h1", "h2", "h3"]; let articleElement = document.querySelector(props.container); if (!articleElement) { return titles; } let elements = Array.from(articleElement.querySelectorAll("*")); // 調(diào)整標(biāo)簽等級 let tagNames = new Set( elements.map((el) => el.tagName.toLowerCase()) ); for (let i = levels.length - 1; i >= 0; i--) { if (!tagNames.has(levels[i])) { levels.splice(i, 1); } } let serialNumbers = levels.map(() => 0); for (let i = 0; i < elements.length; i++) { const element = elements[i]; let tagName = element.tagName.toLowerCase(); let level = levels.indexOf(tagName); if (level == -1) continue; let id = tagName + "-" + element.innerText + "-" + i; let node = { id, level, parent: null, children: [], rawName: element.innerText, scrollTop: element.offsetTop, }; if (titles.length > 0) { let lastNode = titles.at(-1); // 遇到子標(biāo)題 if (lastNode.level < node.level) { node.parent = lastNode; lastNode.children.push(node); } // 遇到上一級標(biāo)題 else if (lastNode.level > node.level) { serialNumbers.fill(0, level + 1); let parent = lastNode.parent; while (parent) { if (parent.level < node.level) { parent.children.push(node); node.parent = parent; break; } parent = parent.parent; } } // 遇到平級 else if (lastNode.parent) { node.parent = lastNode.parent; lastNode.parent.children.push(node); } } serialNumbers[level] += 1; let serialNumber = serialNumbers.slice(0, level + 1).join("."); node.isVisible = node.parent == null; node.name = serialNumber + ". " + element.innerText; titles.push(node); } return titles; } // 監(jiān)聽滾動事件并更新樣式 window.addEventListener("scroll", function () { progress.value = parseInt( (window.scrollY / document.documentElement.scrollHeight) * 100 ) + "%"; let visibleTitles = []; for (let i = titles.length - 1; i >= 0; i--) { const title = titles[i]; if (title.scrollTop <= window.scrollY) { if (currentTitle.id === title.id) return; Object.assign(currentTitle, title); // 展開節(jié)點(diǎn) setChildrenVisible(title, true); visibleTitles.push(title); // 展開父節(jié)點(diǎn) let parent = title.parent; while (parent) { setChildrenVisible(parent, true); visibleTitles.push(parent); parent = parent.parent; } // 折疊其余節(jié)點(diǎn) for (const t of titles) { if (!visibleTitles.includes(t)) { setChildrenVisible(t, false); } } return; } } }); // 設(shè)置子節(jié)點(diǎn)的可見性 function setChildrenVisible(title, isVisible) { for (const child of title.children) { child.isVisible = isVisible; } } // 滾動到指定的位置 function scrollToView(scrollTop) { window.scrollTo({ top: scrollTop, behavior: "smooth" }); } return { titles, currentTitle, progress, scrollToView }; }, props: { container: { type: String, default: ".post-body .article-content", }, }, }; </script> <style lang="less" scoped> .catalog-card { background: white; border-radius: 8px; box-shadow: 0 3px 8px 6px rgba(7, 17, 27, 0.05); padding: 20px 24px; width: 100%; margin-top: 25px; box-sizing: border-box; } .catalog-card-header { text-align: left !important; margin-bottom: 15px; display: flex; justify-content: space-between; align-items: center; } .catalog-icon { font-size: 18px; margin-right: 10px; color: dodgerblue; } .catalog-card-header div > span { font-size: 17px; color: #4c4948; } .progress { color: #a9a9a9; font-style: italic; font-size: 140%; } .catalog-content { max-height: calc(100vh - 120px); overflow: auto; margin-right: -24px; padding-right: 20px; } .catalog-item { color: #666261; margin: 5px 0; line-height: 28px; cursor: pointer; transition: all 0.2s ease-in-out; font-size: 14px; padding: 2px 6px; display: -webkit-box; overflow: hidden; text-overflow: ellipsis; -webkit-line-clamp: 1; -webkit-box-orient: vertical; &:hover { color: #1892ff; } } .active { background-color: #; color: white; &:hover { background-color: #0c82e9; color: white; } } </style>
到此這篇關(guān)于使用 Vue3 實(shí)現(xiàn)文章目錄功能的文章就介紹到這了,更多相關(guān)Vue3文章目錄內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
VUE項(xiàng)目調(diào)用高德地圖的詳細(xì)步驟
要在Web頁面中加入地圖,我推薦你使用高德地圖JSAPI,下面這篇文章主要給大家介紹了關(guān)于VUE項(xiàng)目調(diào)用高德地圖的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-05-05vite項(xiàng)目vite.config.js詳細(xì)配置
vite.config.js是Vite框架中的配置文件,用于配置項(xiàng)目的構(gòu)建和運(yùn)行時(shí)的行為,下面這篇文章主要給大家介紹了關(guān)于vite項(xiàng)目vite.config.js詳細(xì)配置的相關(guān)資料,需要的朋友可以參考下2023-05-05vue項(xiàng)目 npm run build 打包項(xiàng)目防止瀏覽器緩存的操作方法
這篇文章主要介紹了vue項(xiàng)目 npm run build 打包項(xiàng)目防止瀏覽器緩存的操作方法,本文給大家推薦兩種方法,每種方法通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08vue.js中toast用法及使用toast彈框的實(shí)例代碼
這篇文章主要介紹了vue.js中toast用法及使用toast彈框的實(shí)例代碼,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒加載,需要的朋友可以參考下2018-08-08解決創(chuàng)建vue項(xiàng)目后沒有vue.config.js文件的問題
這篇文章給大家主要介紹如何解決創(chuàng)建vue項(xiàng)目后沒有webpack.config.js(vue.config.js)文件,文中有詳細(xì)的解決方法,感興趣的朋友可以參考閱讀下2023-07-07