我正在开发一个单页应用的Vue.js/Laravel8项目,并且无法通过VueRouter实现页面滚动到我想要的section。该页面由不同的section组成,当用户向下滚动时可以访问这些section,我希望视口类似于标记的工作方式,可以滚动到某个section。
如何使
<router-link :to="{ name: section1 }">Section1</router-link>
表现得像
<a href="#section1">Section1</a>
?
我尝试了以下方法:
app.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
});
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
}
}
}
});
web.php:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/{any}', function () {
return view('welcome');
})->where('any', '.*');
app.vue:
<template>
<div class="container">
<main>
<home></home>
<section1></section1>
</main>
<router-view></router-view>
</div>
</template>
navigation.vue:
<template>
<div class="navbar">
<router-link :to="{ name: 'section1' }">Section1</router-link>
</div>
</template>
section1.vue:
<template>
<section id="section1" class="section1">
<div class="image"></div>
</section>
</template>
标签在浏览器中正确转换为标签,VueRouter会将以下属性应用于单击的锚点:
class="router-link-exact-active"
class="router-link-active"
aria-current="page"
但是视口仍然没有滚动到所需的部分。我做错了什么?
name: 'section1'
替换为hash: 'section1'
即可使滚动工作正常。有没有办法从浏览器URL的/#section1
中删除丑陋的#
符号? - Artur Müller Romanov