需求描述
从列表页,进入详情页面,点击返回按钮,定位到原始列表页中对应详情列表项位置。
实现方案
- 列表页:使用锚点定位实现。列表页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(`#anc