详解Vue项目中实现锚点定位
时间:2020-10-06 21:54:44|栏目:vue|点击: 次
背景
今天在开发限时练-提分加项目的时候,有一个需要锚点定位的需求,而在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分页插件的前后端配置与使用
栏 目:vue
下一篇:Vue+webpack+Element 兼容问题总结(小结)
本文标题:详解Vue项目中实现锚点定位
本文地址:http://www.codeinn.net/misctech/7673.html