Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue锚点定位

作者:至尊巅峰   发布日期:2026-06-09   浏览:148

<template>
  <div>
    <nav>
      <ul>
        <li><a href="#section1">Section 1</a></li>
        <li><a href="#section2">Section 2</a></li>
        <li><a href="#section3">Section 3</a></li>
      </ul>
    </nav>

    <section id="section1">
      <h2>Section 1</h2>
      <p>This is the first section.</p>
    </section>

    <section id="section2">
      <h2>Section 2</h2>
      <p>This is the second section.</p>
    </section>

    <section id="section3">
      <h2>Section 3</h2>
      <p>This is the third section.</p>
    </section>
  </div>
</template>

<script>
export default {
  name: 'AnchorExample',
  mounted() {
    // Smooth scroll to anchor when hash changes
    window.addEventListener('hashchange', this.scrollToHash);
  },
  methods: {
    scrollToHash() {
      const id = window.location.hash.slice(1);
      if (id) {
        const element = document.getElementById(id);
        if (element) {
          element.scrollIntoView({ behavior: 'smooth' });
        }
      }
    }
  },
  beforeDestroy() {
    window.removeEventListener('hashchange', this.scrollToHash);
  }
};
</script>

<style scoped>
section {
  height: 100vh;
  margin-bottom: 20px;
}

nav ul {
  list-style-type: none;
  padding: 0;
}

nav ul li {
  display: inline;
  margin-right: 10px;
}
</style>

解释说明:

  1. 模板部分 (<template>):

    • 导航栏 (<nav>) 包含三个链接,分别指向页面中的不同部分(#section1, #section2, #section3)。
    • 页面中定义了三个 <section> 元素,每个元素都有一个唯一的 id 属性,对应导航栏中的链接。
  2. 脚本部分 (<script>):

    • 在组件挂载时 (mounted 钩子),添加了一个监听器来监听 URL 的 hash 变化 (window.addEventListener('hashchange', this.scrollToHash)).
    • scrollToHash 方法用于平滑滚动到对应的锚点位置。它通过 window.location.hash 获取当前的锚点 ID,并使用 element.scrollIntoView({ behavior: 'smooth' }) 实现平滑滚动。
    • 在组件销毁前 (beforeDestroy 钩子),移除监听器以防止内存泄漏。
  3. 样式部分 (<style scoped>):

    • 简单的样式设置,使每个 section 占据整个视口高度 (height: 100vh),并且导航栏的链接水平排列。

上一篇:vue表格

下一篇:electron+vue

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

vue.min.js 本地引入

vue.js 3

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js devserv

vue.config.js transpi

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站