javascript - VueRouter 不滚动到锚标签
问题描述
我正在做一个Vue.js/Laravel8
项目,single page app
但无法VueRouter
滚动到section
我想要的。该页面由不同的组成,sections
如果用户向下滚动并且我希望viewport
滚动到section
类似于<a>
标签的工作方式,则可以访问这些页面。
我该怎么做
<router-link :to="{ name: section1 }">Section1</router-link>
表现得像
<a href="#section1">Section1</a>
?
我尝试了以下方法:
应用程序.js:
require('./bootstrap')
import Vue from "vue"
import App from "../vue/app"
import router from "./router";
const app = new Vue({
el: "#app",
components: { App },
router
});
路由器.js:
import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../vue/home";
import Section1 from "../vue/section1";
Vue.use(VueRouter);
export default new VueRouter ({
mode: "history",
base: process.env.BASE_URL,
routes: [
{path: "/", name: "home"},
{path: "/section1", name: "section1", component: Section1},
],
scrollBehavior(to, from, savedPosition) {
console.log(savedPosition)
if (savedPosition) {
return savedPosition;
} else if (to.hash) {
return {
selector: to.hash
}
}
}
});
网页.php:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/{any}', function () {
return view('welcome');
})->where('any', '.*');
应用程序.vue:
<template>
<div class="container">
<main>
<home></home>
<section1></section1>
</main>
<router-view></router-view>
</div>
</template>
导航.vue:
<template>
<div class="navbar">
<router-link :to="{ name: 'section1' }">Section1</router-link>
</div>
</template>
第1节.vue:
<template>
<section id="section1" class="section1">
<div class="image"></div>
</section>
</template>
<router-link>
<a>
标签在浏览器中被正确转换为标签,并VueRouter
适用properties
于 clicked anchor
:
class="router-link-exact-active"
class="router-link-active"
aria-current="page"
但是仍然viewport
没有滚动到所需的位置section
。我究竟做错了什么?
解决方案
尝试使用名称的路径并将哈希添加到链接:
<router-link :to="{ path: '/section1', hash: '#section1' }">Section1</router-link>
推荐阅读
- powershell - 如何在 PowerShell 中隔离并携带一段变量字符串
- javascript - RxJS - 将“对象”事件转换为包含所有对象的“数组”
- excel - SUMIF 公式使用不同格式的数据(UK 格式)
- javascript - 关于 lerna monorepo 和 styled-components 的概念问题
- php - Laravel validateForm:不活动时防止更新
- python - 为什么我的分页不起作用?(姜戈)
- angular - 如何获取 Angular Material 对话框的当前位置
- python-3.x - 如何在 Python 上使用 Mesa 和 Networkx 获取节点之间的距离?
- axios - 如何在axios中获取响应状态码?标准解决方案不起作用
- ruby-on-rails - 当每个案例都有不同的样式时如何从 Rails 视图中删除逻辑