Vue从详情页返回列表页,页面定位到该详情页对应列表项位置

需求描述

从列表页,进入详情页面,点击返回按钮,定位到原始列表页中对应详情列表项位置。

实现方案

  • 列表页:使用锚点定位实现。列表页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
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值