详解Vue项目中实现锚点定位
人气:0背景
今天在开发限时练-提分加项目的时候,有一个需要锚点定位的需求,而在Vue项目中,使用传统的在a标签的href属性中写id的方法无效,会导致浏览器的地址改变从而跳转到其他页面。
解决
最终参考vue2.0中怎么做锚点定位改问题下的回答实现了效果。
<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: ["整体分析", "错题整理", "提分训练"], activeBtn: 0 }; }, mounted() { this.dataInit(); }, methods: { ...mapActions("v2-score-preview", [ "fetchClassScoreData", "fetchPersonalReportData", "fetchErrorQuestionData", "fetchExerciseData" ]), //初始化 dataInit() { this.fetchClassScoreData(); this.fetchPersonalReportData(); this.fetchErrorQuestionData(); this.fetchExerciseData(); }, //锚点跳转 goAnchor(selector, index) { this.activeBtn = index; document.querySelector("#app-root").scrollTop = this.$el.querySelector(selector).offsetTop; } } }; </script>
另外,参考页面内锚点定位及跳转方法总结文章中的第四种方法,发现使用scrollIntoView()方法也能实现锚点定位的效果。
//锚点跳转 goAnchor(selector, index) { this.activeBtn = index; this.$el.querySelector(selector).scrollIntoView() }
以上所述是小编给大家介绍的Vue项目中实现锚点定位详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
您可能感兴趣的文章:
加载全部内容