所以我有一个使用Vue和Vue路由器的SPA。它的设置类似于iOS应用,当您在视图中单击得更深时,导航栏中的标题就会更改。现在,我已经在routes.js文件中对此进行了硬编码,但希望使它成为动态的。我可以在视图中更新路线元,但是会在视图显示后进行渲染,因此我需要在更改路线之前进行。这是设置:
route.js
//A route
{
path: '/team/:username',
component: require('./views/team-single'),
name: 'profile',
meta:{ requiresAuth: true, title: 'Team Member', tabbar: false }
}
Run Code Online (Sandbox Code Playgroud)
导航栏
//if the route has a title show that not the logo
<div class="navbar-item">
<transition name="fadeup">
<h1 v-if="$route.meta.title" class="navbar-title">{{ $route.meta.title }}</h1>
<img src="/img/hopbak-green.svg" class="navbar-logo" alt="hopbak" v-else>
</transition>
</div>
Run Code Online (Sandbox Code Playgroud)
因此,理想情况下,最好将:username传递到route.js的标题中,但我认为这不可能。我曾尝试在视图中添加类似的内容,但是就像我说的那样,它被调用到很晚:
团队成员
mounted(){
this.$route.meta.title = this.user.username
}
Run Code Online (Sandbox Code Playgroud)
确实会更改它,但不会在导航栏加载之前更改。
fli*_*eid 10
我在元数据中遇到了动态 url 参数的类似问题,我通过评估this.$routeas 函数的元属性解决了这个问题。先这样配置meta属性:
//A route
{
path: '/team/:username',
component: require('./views/team-single'),
name: 'profile',
meta: (route) => ({ requiresAuth: true, title: 'Team Member' + route.params.username, tabbar: false })
}
Run Code Online (Sandbox Code Playgroud)
然后你可以在你的模板中以这种方式使用它:
//if the route has a title show that not the logo
<div class="navbar-item">
<transition name="fadeup">
<h1 v-if="$route.meta != null" class="navbar-title">{{ $route.meta($route).title }}</h1>
<img src="/img/hopbak-green.svg" class="navbar-logo" alt="hopbak" v-else>
</transition>
</div>
Run Code Online (Sandbox Code Playgroud)
您可以用来props实现类似的目标。
{
path: '/team/:username',
name: 'profile',
component: require('./views/team-single'),
props: (route) => ({ title: route.params.username })
}
Run Code Online (Sandbox Code Playgroud)
并且,在组件中:
props: ['title'],
...
mounted () {
console.log('title: ' + this.title)
}
...
Run Code Online (Sandbox Code Playgroud)
查看文档了解更多信息:https ://router.vuejs.org/en/essentials/passing-props.html
设置完元数据后,我强制路由器像这样重新加载:
this.$route.meta.title = this.user.username
// Add a temporary query parameter.
this.$router.replace({query: {temp: Date.now()}})
// Remove the temporary query parameter.
this.$router.replace({query: {temp: undefined}})
Run Code Online (Sandbox Code Playgroud)
有许多解决方法可以强制重新加载此 GitHub问题中的路由器。这只是其中之一。
| 归档时间: |
|
| 查看次数: |
8983 次 |
| 最近记录: |