欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue3哈希模式實現(xiàn)錨點導航方式

 更新時間:2024年04月28日 09:04:37   作者:小智學前端  
這篇文章主要介紹了Vue3哈希模式實現(xiàn)錨點導航方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

vue3利用哈希模式實現(xiàn)錨點導航

在Vue.js應用中,實現(xiàn)哈希模式的錨點導航是一項常見而有用的功能。

通過哈希模式,我們可以在頁面間快速跳轉,而無需重新加載整個頁面,這對于提升用戶體驗尤為重要。

本文將介紹如何在Vue應用中利用哈希模式實現(xiàn)錨點導航,并且結合CSDN的使用進行詳細說明。

準備工作

首先,確保你的Vue項目已經(jīng)初始化,并且已經(jīng)安裝了Vue Router。

如果還沒有安裝Vue Router,你可以通過以下命令進行安裝:

設置路由

在Vue Router中,我們需要將路由模式設置為哈希模式。

在創(chuàng)建Vue Router實例時,可以通過設置mode: 'hash'來啟用哈希模式。

// router/index.js

import { createRouter, createWebHashHistory,  RouteRecordRaw } from "vue-router";

export const routes: Array<RouteRecordRaw> = [
	...
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

export default router;

組件使用

<script setup lang="ts">
const scrollToAnchor = (data: string) => {
  // 從完整路徑中解析出真正的錨點部分
  const hash = data; // 注意:根據(jù)你的URL結構調整索引
  if (hash) {
    const element = document.getElementById(hash);
    if (element) {
      element.scrollIntoView({ behavior: "smooth" });
    }
  }
};

const onLiclick = (event: any) => {
  scrollToAnchor(event.target.dataset.hash);
};
</script>
<template>
  <div>
    <nav>
      <ul @click="onLiclick">
        <li data-hash="my-box">首頁</li>
        <li data-hash="chanpin-box">產(chǎn)品介紹</li>
        <li data-hash="news-box">實時新聞</li>
        <li data-hash="about-box">關于我們</li>
        <li data-hash="lianxi-box">聯(lián)系我們</li>
      </ul>
    </nav>
    <div class="pages">
      <div id="my-box">
        <h1>我的</h1>
      </div>
      <div id="chanpin-box">
        <h1>產(chǎn)品介紹</h1>
      </div>
      <div id="news-box">
        <h1>實時新聞</h1>
      </div>
      <div id="about-box">
        <h1>關于我們</h1>
      </div>
      <div id="lianxi-box">
        <h1>聯(lián)系我們</h1>
      </div>
    </div>
  </div>
</template>
<style scoped lang="scss">
ul {
  display: flex;
  position: fixed;
  z-index: 999;
  margin: auto;
  left: 50%;
  li {
    cursor: pointer;
    padding: 10px 20px;
  }
}
h1 {
  margin: 0px;
}
</style>

總結

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

最新評論