vue锚链接跳转

本文介绍了在Vue中处理锚链接的方法,特别是在使用vue-router时的滚动行为。重点参考了vue-router官方文档中的scrollBehavior选项,用于实现异步滚动。内容包括在组件间的跳转示例以及router/index.js中的配置代码。旨在帮助开发者解决Vue锚链接问题,鼓励共同学习与交流。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在vue中的锚链接和普通的html不同,关于vue中的锚链接可以参考vue 中的 scrollBehavior 滚动行为
链接地址:https://router.vuejs.org/zh/guide/advanced/scroll-behavior.html#异步滚动

组件一

<template>
	<div class="hello">
		<header>
			<div v-for="(item,index) in nav" :key='index' class="g-box" @mouseenter='enter(index)' @mouseleave='leave()'>
				<router-link :to="item.path">
					{{item.name}}
				</router-link>
				<div class="hide" v-show="see&&index == current">
					<p v-for="(it,index) in item.cli" :key='index'>
						<a :href="it.sid">{{it.title}}</a>
					</p>
				</div>
			</div>
		</header>
	</div>
</template>
<script>
	export default {
		name: 'HelloWorld',
		data() {
			return {
				nav: [{
					name: '首页',
					path: '/'
				}, {
					name: '关于我们',
					path: '/about',
					cli: [{
						title: '品牌历史',
						sid: '/about?#a'
					}, {
						title: '售后服务',
						sid: '/about?#b'
					}, {
						title: '关于我们',
						sid: '/about?#c'
					}]
				}],
				see: false,
				current: 0
			}
		},
		methods: {
			enter(index) {
				// alert(1)
				this.see = true
				this.current = index
			},
			leave() {
				this.see = false
				this.current = null
			}
		}
	}
</script>

组件二

template>
	<div class="page">
		<div class="g-about-box" id="a">
			<p>品牌历史</p>
		</div>
		<div class="g-about-box" id="b">
			<p>售后服务</p>
		</div>
		<div class="g-about-box" id="c">
			<p>关于我们</p>
		</div>
	</div>
</template>

在router文件夹下的index.js添加以下内容

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
	scrollBehavior(to,from,savedPosition) {
		if(to.hash){
			return{
				selector: to.hash
			}
		}
	}
})

如有问题欢迎大家指正,一起学习。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值