问题:
项目中会有一些功能需要用到锚点定位,比如文章目录、点击标题跳转到正文内容等等。但vue的路由设置默认为hash模式,正常使用a标签的锚点定位,在浏览器刷新/后退/前进时,路由会匹配不上,导致页面无法正常渲染
解决方案:
方法一:
在router配置里添加(亲测有效):
mode: 'history',
srcollBehavior(to,from,savedPosition){
if(to.hash){
return {
selector:to.hash
}
}
}
方法二:
定义点击事件
<template>
<div>
<div><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" @click="goAnchor('#anchor-'+index)" v-for="index in 20"> {
{index}</a></div>
<div :id="'anchor-'+index" class="item" v-for="index in 20">{
{index}</div>
</div>
</template>
methods: {
goAnchor(selector) {
var anchor = this.$el.querySelector(selector)
document.documentElement.scrollTop = anchor.offsetTop
}
}
方法三:
自定义指令
<template>
<div>
<div><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" v-anchor="index" v-for="index in 20"> {
{index}} </a></div>
<div :id="'anchor-'+index" class="item" v-for="index in 20" >{
{index}}</div>
</div>
</template>
main.js 定义全局指令 方便其他地方复用
Vue.directive('anchor',{
inserted : function(el,binding){
el.onclick = function(){
document.documentElement.scrollTop = $('#anchor-'+binding.value).offset().top
}
}
})
方法四:
定义点击事件
document.querySelector(“要返回地方的id”).scrollIntoView(true);
<template>
<div>
<div id='header'></div>
<div class='footer' @click='returnTop'></div>
</div>
</template>
methods:{
returnTop(){
document.querySelector("#header").scrollIntoView(true);
}
}
拓展:
scrollIntoView是一个与页面(容器)滚动相关的API(官方解释),该API只有boolean类型的参数能得到良好的支持(firefox 36+都支持),所以在这里只讨论参数Boolean类型的情况。
调用方法为 element.scrollIntoView() 参数默认为true。
参数为true时调用该函数,页面(或容器)发生滚动,使element的顶部与视图(容器)顶部对齐;
参数为false时,使element的底部与视图(容器)底部对齐。
TIPS:页面(容器)可滚动时才有用!