在Vue中實現文章錨點功能,可以通過監聽滾動事件來更新當前錨點的狀態。以下是一個簡單的示例:
<template><div><div :id="'anchor-' + index" v-for="(section, index) in sections" :key="index">{{ section.title }}</div><ul class="nav nav-pills"><li v-for="(section, index) in sections" :key="index"><p @click="scrollToAnchor(index)" :style="{ color: (activeAnchor === index)?'red':'black' }">{{ section.title }}</p></li></ul></div>
</template>
<script>
export default {data() {return {activeAnchor: 0,sections: [{ title: 'Section 1' },{ title: 'Section 2' },{ title: 'Section 3' },// ...],};},mounted() {window.addEventListener('scroll', this.updateActiveAnchor);this.updateActiveAnchor(); // 初始調用以設置初始活動錨點},beforeDestroy() {window.removeEventListener('scroll', this.updateActiveAnchor);},methods: {//滾動到錨點位置scrollToAnchor(index) {const anchorElement = document.getElementById('anchor-' + index);if (anchorElement) {//anchorElement.scrollIntoView({ behavior: 'smooth' }); 頂欄遮住了錨點const fixedBarHeight = 63; // 假設頂欄高度pxwindow.scrollTo({top: anchorElement.offsetTop - fixedBarHeight,behavior: 'smooth'});}},//根據屏幕滾動,顯示當前活動錨點updateActiveAnchor() {this.sections.forEach((section, index) => {const element = document.getElementById('anchor-' + index);const fixedBarHeight = 63; // 假設頂欄高度是pxif (element && window.scrollY >= element.offsetTop-fixedBarHeight) {this.activeAnchor = index;}});},},
};
</script>
在這個示例中,我們定義了一個sections數組來表示文章的不同部分。每個部分都有其對應的標題和唯一的ID。我們還維護了一個activeAnchor狀態,它表示當前活動錨點的索引。
在模板中,我們使用v-for來遍歷sections數組,并為每個部分創建一個可以滾動到的div元素。我們還創建了一個導航列表,其中包含了所有錨點的鏈接,并使用active類來表示當前活動的錨點。
在mounted鉤子中,我們添加了一個事件監聽器來監聽滾動事件,并調用updateActiveAnchor方法來更新當前活動的錨點。在beforeDestroy鉤子中,我們移除了這個事件監聽器。
scrollToAnchor方法接收一個索引,并滾動到對應的錨點。updateActiveAnchor方法遍歷所有錨點,并根據當前窗口的滾動位置來設置activeAnchor的值。