【发布时间】: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>
<router-link>标签在浏览器中正确转换为<a>标签,VueRouter将properties后面的properties应用于点击的anchor:
class="router-link-exact-active"
class="router-link-active"
aria-current="page"
但是viewport 仍然没有滚动到所需的section。我做错了什么?
【问题讨论】:
标签: javascript php laravel vue.js vue-router