2016-11-17 149 views
3

如何在通過ajax獲取路由之後動態創建路由數組?vue-router 2,如何通過ajax獲取路由?

有沒有辦法在路由器初始化後向路由器添加/推送新路由?

這不起作用:

new Vue({ 
    el: '#app', 
    template: '<App/>', 
    data: { 
    content: [] 
    }, 
    created: function() { 
    this.$http.get('dummyjsondatafornow').then((response) => { 

     // this doesn't work when creating the VueRouter() outside the Vue instance, as in the docs. 
     // this.$router.options.routes.push({ path: '/about', component: About }) 

     let routes = [ 
     { path: '/about', component: About } 
     ] 

     // this doesn't work either 
     this.router = new VueRouter({ 
     routes: routes 
     }) 
    }) 
    }, 
    // router: router, 
    components: { App } 
}) 
+0

我可以理解爲創建服務器端動態路由,而是動態的路線SPA?重點在哪裏? –

+0

那麼,SPA的內容(包括頁面/路線)將在獨立系統(CMS)中進行管理。我還能怎麼解決這個問題? – Emin

回答

3

我不相信就沒有了。

那就是說你可以通配這條路線,這樣可以爲你提供一個選擇。

我建立了一個網站,通過一個內容管理系統(CMS)控制後端(並反過來創建頁面),該網站將所有頁面作爲JSON提供給Vue。這意味着Vue沒有意識到後端創建的路線。

相反,我們通過一個*通配符組件將所有CMS頁面傳遞給Vue路由器。在Vue公司路由器2,這將是這樣的:

const routes = [ 
    { path: '*', component: AllPages } 
] 

Vue的路由器2允許Advanced Matching Patterns

這允許你設置各種各樣的條件,因此雖然你不能注入通過AJAX傳回的對象到你的路由器中,你可以添加一個動態組件到通配符匹配的AllPages組件。這將允許您傳遞組件的名稱以通過您的ajax請求加載,然後在調用頁面時加載該組件。即

你的Ajax響應:

{ 
    // url: component name 
    '/about/': 'about', 
    '/about/contact/': 'contact', 
    ... 
} 

然後在所有頁VUE組件:

<template> 
    <component v-bind:is="currentView"></component> 
</template> 

<script> 

    module.exports = { 
    data() { 
     return { 
     currentView: '', 
     ajaxRoutes: {}, // loaded via ajax GET request 
     ... 
     } 
    }, 
    // watch $route to detect page requests 
    watch: { 
     '$route' (to, from) { 
     if (this.ajaxRoutes[to]) { 
      this.currentView = this.ajaxRoutes[to] 
     } 
     } 
    }, 
    ... 
    } 

</script> 

以上是一個比較簡短的想法,但實際上你動態地基於路徑的用戶上加載組件請求。

+0

謝謝你的精心解答!這似乎是我正在尋找的。 – Emin