问题:
项目中会有一些功能需要用到锚点定位,比如文章目录、点击标题跳转到正文内容等等。但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:页面(容器)可滚动时才有用!
Hi there. Yes, I created this site myself, and appreciate the commentary! Mersey Rocky Crispin
Good write-up. I absolutely appreciate this website. Continue the good work! Germana Brent Terchie
hi!,I really like your writing so so much! share we keep up a correspondence more approximately your post on AOL? I need a specialist on this area to unravel my problem. May be that is you! Looking ahead to look you. Peg Dana Kuehnel
Pretty nice post. I just stumbled upon your weblog and wanted to say that I have truly enjoyed surfing around your blog posts. After all I will be subscribing to your feed and I hope you write again very soon! Shirlee Leroy Mallory
Excellent beat ! I would like to apprentice while you amend your web site, how could i subscribe for a blog website? The account aided me a acceptable deal. I had been tiny bit acquainted of this your broadcast provided bright clear idea Amye Zebadiah Seraphim
Thank you for the good writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! However, how can we communicate? Lesley Wilfred Adlee
I was very happy to uncover this web site. I wanted to thank you for your time for this particularly wonderful read!! I definitely savored every little bit of it and i also have you saved as a favorite to check out new information on your web site. Amil Nicolais Gibby