vue跨页面跳转到相应锚点处
路由
{
path: '/product/tutorlals',
name: 'Products_tutorlals',
component: Products_tutorlals
},
product页面
<router-link :to="{name:'Products_tutorlals',query: {maodian:'tutorials'+item.id}}">
<div class="moretutorials">
More Tutorials >
</div>
</router-link>
product_tutorlals页面
<ul class="Tutorial cl">
<li class="Tutorialli" :id="'tutorials'+item.id" :ref="'tutorials'+item.id" v-for="(item, index) in tutoriallist" :key="item.id">
<div class="Tutorialleft">
<img :src="item.cover.indexOf('http')==-1?imageurl+item.cover:item.cover" alt="" class="img">
</div>
<div class="Tutorialright">
<div class="name">
{{item.name}}
</div>
<ul class="details">
<li class="detailsli cl" v-for="(item, index) in item.video" :key="item.id">
<router-link :to="{name:'Products_video_detail',params: {id:item.id}}">
<div>
<div class="qiu">
</div>
<div class="detailstext">
{{item.title}}
</div>
</div>
</router-link>
</li>
</ul>
</div>
</li>
</ul>
product_tutorlals内引入common.js文件
import { goAnchor, GetQueryString } from "@/js/common";
product_tutorlals页面内的方法
//用updated(更新完成)这个钩子函数是为了页面完全加载之后找到含有锚点的id
updated: function() {
let maodian = this.GetQueryString("maodian"); //进入页面,如果带有锚点参数,则跳转至锚点地方,参数值就是id名
this.$nextTick(() => {
if (maodian) {
this.goAnchor(maodian);
}
});
},
methods: {
initData() {
tutorialmorerequest().then(res => {
if ((res.code = 100000)) {
this.tutoriallist = res.data.data;
}
});
},
goAnchor,
GetQueryString
},
product_tutorlals页面引入的common.js
//跳转到锚点
function goAnchor(selector) {
console.info("selector1", selector)
// var anchor = this.$el.querySelector(selector);//获取元素
var anchor = this.$refs[selector][0];//获取元素
console.info("anchor", anchor)
console.log(this.$refs.rrrr,"333")
if (anchor) {
setTimeout(() => {//页面没有渲染完成时是无法滚动的,因此设置延迟
//anchor.scrollIntoView(); //js的内置方法,可滚动视图位置至元素位置
var targetOffset = $("#"+selector).offset().top;
console.info("targetOffset", anchor, targetOffset)
$('html,body').animate({
scrollTop: targetOffset
},
1000);
}, 500);
}
};
//获取参数
function GetQueryString(name) {
//var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var href = window.location.href;
var r = getSearchString(name, href);
if (r != null) return decodeURI(r);
return null;
}
function getSearchString(key, Url) {
var str = Url;
str = str.substring(1, str.length);
if (str.indexOf("?") != -1) {
var arr = str.split("?")[1].split("&");// 获取?后的参数内容,并以&分隔字符串,获得类似name=xiaoli这样的元素数组
var obj = new Object();
// 将每一个数组元素以=分隔并赋给obj对象
for (var i = 0; i < arr.length; i++) {
var tmp_arr = arr[i].split("=");
obj[decodeURIComponent(tmp_arr[0])] = decodeURIComponent(tmp_arr[1]);
}
return obj[key];
}
}
export {
goAnchor,
GetQueryString
}