I am working on a Vue.js/Laravel8 project on a single page app and can't get VueRouter to get to scroll to the section I want. The page consists of different sections which are reachable if user scrolls down and I want the viewport to scroll to a section similar to how the <a> tag works.
How do I make
<router-link :to="{ name: section1 }">Section1</router-link>
behave like
<a href="#section1">Section1</a>?
I've tried 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 following properties to the clicked anchor:
class="router-link-exact-active"
class="router-link-active"
aria-current="page"
But the viewport is not scrolling to the desired section still. What am I doing wrong?
Try to use path insted of name and add hash to link:
<router-link :to="{ path: '/section1', hash: '#section1' }">Section1</router-link>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With