gpt4 book ai didi

html - 如何在 Vue 路由器中定义要在组件内部使用的变量?

转载 作者:行者123 更新时间:2023-12-04 15:03:49 25 4
gpt4 key购买 nike

我在顶部有一个导航栏和一个 <router-view>就在它的正下方(如 App.vue 中所示)。我希望导航栏内的标题根据我所在的路线/ View 而改变。由于我在 <router-view> 中的观点不包含标题本身,我需要在某处定义它们。该场景的示例可能是到达路线 /login 时,导航栏中的标题更改为“登录”。我如何实现这一点?

在寻找解决方案时,我遇到了很多页面标题问题。我不是在谈论 document.title然而,这可能是一个解决方案,但不是一个完美的解决方案。如果我希望标题是文档标题以外的东西怎么办..

App.vue:

<template>
<Menu :isActive="isMenuActive" />
<Navbar @toggle:hamburger="onHamburgerToggle($event)" />
<router-view />
</template>

最佳答案

Vue router 允许你使用 Route Meta Fields 将你想要的任何信息附加到任何路由

const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
meta: { title: "FOO" }
}
]
})

您可以使用$route 在任何组件中访问当前事件路由的信息variable

const child = Vue.component('child', {
template: `
<div>
Child component ("{{ $route.meta.title }}")
</div>
`
})

const router = new VueRouter({
mode: 'history',
routes: [
{
name: 'route1',
path: '/route1',
component: child,
meta: { title: 'Hello from route 1!'}
},
{
name: 'route2',
path: '/route2',
component: child,
meta: { title: 'Hello from route 2!'}
},
]
})

new Vue({
el: '#app',
router,
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
<router-link to="/route1">Route 1</router-link>
<router-link to="/route2">Route 2</router-link>

<h4> Current route: {{ $route.meta.title }} </h4>

<router-view></router-view>
</div>

关于html - 如何在 Vue 路由器中定义要在组件内部使用的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66505787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com