首页 > 解决方案 > 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。我究竟做错了什么?

标签: javascriptphplaravelvue.jsvue-router

解决方案


尝试使用名称的路径并将哈希添加到链接:

<router-link :to="{ path: '/section1', hash: '#section1' }">Section1</router-link>

推荐阅读