2017-10-19 1496 views
0

所以我有一個使用Vue和Vue路由器的SPA。它的設置就像一個iOS應用程序,當你更深入點擊視圖時,導航欄中的標題會發生變化。現在我在routes.js文件中有這個硬編碼,但想要使其具有動態性。我可以更新我的視圖中的路由元,但是在視圖顯示之後呈現,所以我需要它在路由更改之前發生。下面是設置:Vue路由器動態設置Meta

route.js

//A route 
{ 
     path: '/team/:username', 
     component: require('./views/team-single'), 
     name: 'profile', 
     meta:{ requiresAuth: true, title: 'Team Member', tabbar: false } 
    } 

navbar.vue

//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> 

所以最好這將是很好打發:用戶名進入在route.js但我標題不認爲這是可能的。我曾嘗試添加一些像這樣的看法,但就像我說的它被稱爲後期:

團隊member.vue

mounted(){ 
    this.$route.meta.title = this.user.username 
} 

這確實改變,但尚未加載導航欄前。

enter image description here

回答

0

你可以使用props來實現這樣的事情。

{ path: '/team/:username', name: 'profile', component: require('./views/team-single'), props: (route) => ({ title: route.params.username }) }

而且,在組件:

... props: ['title'], ... mounted() { console.log('title: ' + this.title) } ...

更多結帳文檔:https://router.vuejs.org/en/essentials/passing-props.html

+0

感謝。一個好的解決方案,但它只會傳遞給組件'team-single'。標題需要在主應用程序佈局中的'navbar'組件中設置。 – Packy

+0

然後,一種方法是從某種商店設置和閱讀標題。結帳https://vuex.vuejs.org/zh/ –