gpt4 book ai didi

javascript - VueRouter 不滚动到 anchor 标签

转载 作者:行者123 更新时间:2023-12-04 17:12:06 24 4
gpt4 key购买 nike

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

24 4 0