詳解Vue項目中實現(xiàn)錨點定位
背景
今天在開發(fā)限時練-提分加項目的時候,有一個需要錨點定位的需求,而在Vue項目中,使用傳統(tǒng)的在a標簽的href屬性中寫id的方法無效,會導(dǎo)致瀏覽器的地址改變從而跳轉(zhuǎn)到其他頁面。

解決
最終參考vue2.0中怎么做錨點定位改問題下的回答實現(xiàn)了效果。
<template>
<div class="score-preview-container">
<div class="content-box">
<div class="content-page-box">
<GlobalAnalysis :id="#anchor-0" />
<ErrorMerge :id="#anchor-1" />
<DoExercise :id="#anchor-2" />
</div>
<div class="nav-button-box">
<span class="nav-button-fix">
<div class="nav-button" v-for="(item,index) in buttonArr" :key="index" :class="{active : activeBtn == index}" @click="goAnchor('#anchor-'+index,index)">{{item}}</div>
</span>
</div>
</div>
</div>
</template>
<script>
import { mapActions } from "vuex";
import GlobalAnalysis from "./components/GlobalAnalysis.vue";
import ErrorMerge from "./components/ErrorMerge.vue";
import DoExercise from "./components/DoExercise.vue";
export default {
name: "score-preview",
components: { GlobalAnalysis, ErrorMerge, DoExercise },
data() {
return {
buttonArr: ["整體分析", "錯題整理", "提分訓(xùn)練"],
activeBtn: 0
};
},
mounted() {
this.dataInit();
},
methods: {
...mapActions("v2-score-preview", [
"fetchClassScoreData",
"fetchPersonalReportData",
"fetchErrorQuestionData",
"fetchExerciseData"
]),
//初始化
dataInit() {
this.fetchClassScoreData();
this.fetchPersonalReportData();
this.fetchErrorQuestionData();
this.fetchExerciseData();
},
//錨點跳轉(zhuǎn)
goAnchor(selector, index) {
this.activeBtn = index;
document.querySelector("#app-root").scrollTop = this.$el.querySelector(selector).offsetTop;
}
}
};
</script>
另外,參考頁面內(nèi)錨點定位及跳轉(zhuǎn)方法總結(jié)文章中的第四種方法,發(fā)現(xiàn)使用scrollIntoView()方法也能實現(xiàn)錨點定位的效果。
//錨點跳轉(zhuǎn)
goAnchor(selector, index) {
this.activeBtn = index;
this.$el.querySelector(selector).scrollIntoView()
}
以上所述是小編給大家介紹的Vue項目中實現(xiàn)錨點定位詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
vue 重塑數(shù)組之修改數(shù)組指定index的值操作
這篇文章主要介紹了vue 重塑數(shù)組之修改數(shù)組指定index的值操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08
修改el-form-item中的label里面的字體邊距或者大小問題
這篇文章主要介紹了修改el-form-item中的label里面的字體邊距或者大小問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10

