需求描述
从列表页,进入详情页面,点击返回按钮,定位到原始列表页中对应详情列表项位置。
实现方案
- 列表页:使用锚点定位实现。列表页dom挂载完成后,判断路由是否有hash,若有页面定位到对应hash的列表项。
<template>
<div>
<ul>
<li v-for="item in list" :key="item.id" :id="`anchor${item.id}`">
<el-button type="primary" round size="small" @click="goDetail(item.id)">查看详情</el-button>
</li>
</ul>
</div>
<template>
created() {
this.goToAnchor()
},
methods: {
//进入详情页
goDetail(id) {
//页面加列表项锚点
location.href = `#${id}`;
this.$router.push({
name: 'detail',
params: {
id: id
}
});
},
//根据页面hash值,定位到指定列表项
goToAnchor() {
if (this.$route.hash && this.list > 0) {
this.$nextTick(() => {
let anchor = this.$el.querySelector(`#anchor${this.$route.hash.slice(1)}`)
if (anchor) {
let offsetY = anchor.offsetTop;
window.scrollTo(0, offsetY)
}
})
}
},
}
- 详情页:考虑链接可以分享出去,故未使用this.$router.go(-1)实现返回功能
goBack() {
this.$router.push({
name: 'list',
hash: `#${this.$route.params.id}`
})
}
注:可以使用vue-scrollto插件实现定位功能
参考
- https://segmentfault.com/q/1010000007888351?_ea=1483516
- https://www.cnblogs.com/jiayeyuan/p/10114205.html
- https://www.jianshu.com/p/950c673bcff9
- https://www.npmjs.com/package/vue-scrollto