2015-12-16 242 views
1

我使用Node + Riot.js + Grapnel路由庫(它可以在客戶端和服務器上工作)。我管理如何在客戶端上設置路由,但我無法確定如何使其在服務器上工作。服務器端渲染+ Riot.js路由?

我的客戶端路由器的當前功能很簡單。我只是發送opts.route到適當的組件,然後它將請求的頁面(也是一個組件)安裝到div

<x-layout> 
    <div id="app-body"></div> 

    <script> 
    this.on('mount update', function() { 
     riot.mount('#app-body', 'x-page-' + opts.route); 
    }); 
    </script> 
</x-layout> 

但隨着riot.render(tag, {page: 'dashboard'})不掛載<x-page-dashboard>#app-body

當我刪除this.on('mount update' ...包裝它給了我一個錯誤

.../node_modules/riot/riot.js:1918 
TypeError: (ctx || document).querySelectorAll is not a function` 

這是顯而易見的,因爲節點不能執行DOM操作。

我也試圖動態加載的部件,像這樣

// Riot doesn't compiles such expressions `<x-page-{opts.route}>` 
var tag = riot.tag2('x-layout', '<div id="app-body"><x-page-{opts.route}></x-page-{opts.route}></div>'); 
riot.render(tag, {route: 'dashboard'}); // --> <x-layout><div id="app-body"><x-page-{opts.route}></x-page-{opts.route}></div></x-layout> 

// Compiles but not mounts (empty tag) 
var tag = riot.tag2('x-layout', '<div id="app-body" riot-tag="x-page-{opts.route}"></div>'); 
riot.render(tag, {route: 'dashboard'}); // --> <x-layout><div id="app-body" riot-tag="x-page-dashboard"></div></x-layout> 

// It's only working when I hard coded the tag name 
var tag = riot.tag2('x-layout', '<x-page-dashboard></x-page-dashboard>'); 
riot.render(tag, {route: 'dashboard'}); // <x-layout><x-page-dashboard>___ CHILDREN COMPONENTS... ____</x-page-dashboard></x-layout> 

有沒有實現同構渲染+路由任何可能的方式?我幾乎在那裏,只需要通過opts動態地通過組件名稱

回答

1

我終於解決了它。解決方案是使用name="app_body"屬性,但不是我正在嘗試執行的id="app-body"

<x-layout> 
    <div name="app_body"></div> 

    <script> 
    this.mountPage = (page) => { 
     riot.mount(this.app_body, 'x-page-' + page); 
    } 

    if (opts.route) 
     this.mountPage(opts.route) 
    </script> 
</x-layout> 

由於GianlucaGuarini響應https://github.com/riot/riot/issues/1450#issuecomment-165984208

工作實施例https://github.com/GianlucaGuarini/riot-app-example