javascript - VueRouter 不滚动到 anchor 标签

标签 javascript laravel vue.js vuejs2 vue-router

我正在研究 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>

我试过以下方法:

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>

导航.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>标签已正确转换为 <a>浏览器中的标签和 VueRouter适用于以下 properties点击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>

关于javascript - VueRouter 不滚动到 anchor 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69236606/

相关文章:

javascript - Vue中用requestAnimationFrame观察滚动位置

javascript - 从 promise 解析调用时 Vuex 存储未更新

javascript - 带有 Rails 3.1 应用程序的初学者问题 : How do I integrate processing. js?

php - 创建后 Laravel 5 Eloquent 加载模型属性

php - 将关联数组做成类似于 Eloquent 查询集合的集合

php - Laravel Eloquent(where 子句)

javascript - Nuxt 和 Vue Apollo。如何处理智能查询内的错误并重定向到 404/400/500 错误页面?我们能捕捉到这样的错误吗?

javascript - Node 中有没有一个好的库用于客户端和服务器之间的异步通信?

javascript - 如何在 google visualization api 柱形图中使用的 json 对象中用数字替换字符串值

javascript - 如何为 HTML、PHP、Javascript、MySQL 中的搜索结果创建 "pages"