I am currently tackling an issue with my Vue.js/Laravel8
project on a single page application
. I am struggling to make the VueRouter
scroll to a specific section
on the page. The page is divided into various sections
that are accessible by scrolling down, and I want the viewport
to automatically scroll to a particular section
similar to how the <a>
tag functions.
How can I configure the following:
<router-link :to="{ name: section1 }">Section1</router-link>
to behave like
<a href="#section1">Section1</a>
?
I have made attempts at the following:
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>
<router-link>
tags are correctly converted into <a>
tags in the browser and VueRouter
applies the following properties
to the clicked anchor
:
class="router-link-exact-active"
class="router-link-active"
aria-current="page"
However, the viewport
still does not scroll to the desired section
. What could be going wrong here?