vue3.0跳转页面指定位置
时间: 2024-03-26 22:30:22 浏览: 20
在Vue3.0中,可以使用`scrollBehavior`函数来指定页面跳转后的滚动位置。具体步骤如下:
1. 在`router/index.js`文件中,添加`scrollBehavior`函数,示例代码如下:
```javascript
const router = createRouter({
history: createWebHistory(),
routes: [...],
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
// 如果浏览器有缓存的滚动位置,则跳转到缓存位置
return savedPosition
} else {
// 否则,如果目标路由配置了滚动位置,则跳转到指定位置
if (to.hash) {
return { selector: to.hash }
}
// 否则,滚动到页面顶部
return { x: 0, y: 0 }
}
}
})
```
2. 在组件的模板中,添加锚点,示例代码如下:
```html
<template>
<div>
<a href="#sectionA">跳转到A</a>
<a href="#sectionB">跳转到B</a>
<!-- ... -->
<section id="sectionA">
<!-- ... -->
</section>
<section id="sectionB">
<!-- ... -->
</section>
<!-- ... -->
</div>
</template>
```