【问题标题】:VueRouter not scrolling to anchor tagsVueRouter 不滚动到锚标签
【发布时间】:2021-11-13 02:38:18
【问题描述】:

我正在处理single page app 上的Vue.js/Laravel8 项目,但无法让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>

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>

&lt;router-link&gt;标签在浏览器中正确转换为&lt;a&gt;标签,VueRouterproperties后面的properties应用于点击的anchor

class="router-link-exact-active"

class="router-link-active"

aria-current="page"

但是viewport 仍然没有滚动到所需的section。我做错了什么?

【问题讨论】:

    标签: javascript php laravel vue.js vue-router


    【解决方案1】:

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

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

    【讨论】:

    • 嘿,这行得通!谢谢你。只需将 name: 'section1' 替换为 hash: 'section1' 即可使滚动工作。有什么方法可以从/#section1 浏览器网址中删除丑陋的# 符号?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 2013-03-29
    • 2013-06-15
    相关资源
    最近更新 更多