Vue3哈希模式實(shí)現(xiàn)錨點(diǎn)導(dǎo)航方式
vue3利用哈希模式實(shí)現(xiàn)錨點(diǎn)導(dǎo)航
在Vue.js應(yīng)用中,實(shí)現(xiàn)哈希模式的錨點(diǎn)導(dǎo)航是一項常見而有用的功能。
通過哈希模式,我們可以在頁面間快速跳轉(zhuǎn),而無需重新加載整個頁面,這對于提升用戶體驗(yàn)尤為重要。
本文將介紹如何在Vue應(yīng)用中利用哈希模式實(shí)現(xiàn)錨點(diǎn)導(dǎo)航,并且結(jié)合CSDN的使用進(jìn)行詳細(xì)說明。
準(zhǔn)備工作
首先,確保你的Vue項目已經(jīng)初始化,并且已經(jīng)安裝了Vue Router。
如果還沒有安裝Vue Router,你可以通過以下命令進(jìn)行安裝:
設(shè)置路由
在Vue Router中,我們需要將路由模式設(shè)置為哈希模式。
在創(chuàng)建Vue Router實(shí)例時,可以通過設(shè)置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) => {
// 從完整路徑中解析出真正的錨點(diǎn)部分
const hash = data; // 注意:根據(jù)你的URL結(jié)構(gòu)調(diào)整索引
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">實(shí)時新聞</li>
<li data-hash="about-box">關(guān)于我們</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>實(shí)時新聞</h1>
</div>
<div id="about-box">
<h1>關(guān)于我們</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>
總結(jié)
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解Vue用axios發(fā)送post請求自動set cookie
本篇文章主要介紹了Vue用axios發(fā)送post請求自動set cookie,非常具有實(shí)用價值,需要的朋友可以參考下2017-05-05
vue2結(jié)合echarts實(shí)現(xiàn)一個地圖的效果
這篇文章主要介紹了vue2結(jié)合echarts實(shí)現(xiàn)一個地圖的效果,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家何用vue和echarts實(shí)現(xiàn)一個地圖有一定的幫助,感興趣的朋友一起看看吧2024-03-03
解決vue接口數(shù)據(jù)賦值給data沒有反應(yīng)的問題
今天小編就為大家分享一篇解決vue接口數(shù)據(jù)賦值給data沒有反應(yīng)的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
查看vue-cli腳手架的版本號和vue真實(shí)版本號及詳細(xì)操作命令
本文給大家分享如何查看vue-cli腳手架的版本號和vue真實(shí)版本號及詳細(xì)操作過程,本文給大家講解的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2022-11-11
復(fù)刻畫龍產(chǎn)品vue實(shí)現(xiàn)新春氣泡兔
這篇文章主要為大家介紹了復(fù)刻畫龍產(chǎn)品之使用vue實(shí)現(xiàn)新春氣泡兔示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01

