2017-08-18 34 views
0

在Aurelia中,當我想訪問作爲aurelia自定義元素的DOM元素的視圖模型時,我可以使用Aurelia重視的au屬性,如componentElement.au.controller.viewModel獲取無容器元素的ViewModel

當我的自定義元素是無容器的(屬性級別爲屬性@containerless)時,屬性au不可用。

這個要點說明了這一點: https://gist.run/?id=928f97f49c01c1db10d8bf4399f5c335

如何訪問一個無容器自定義組件的視圖模型時,我只需要它的DOM元素的引用?

回答

0

達到你想要掛接到created生命週期在您的視圖模型是什麼:

class ViewModel { 
    created(owningView, view) { 
    view.controller 
    view.controller.viewModel // <-- this is what you want 
    } 
} 
+0

如果'不太comp'這樣做,那麼'view.controller'是'undefined'。我猜是因爲它是無容器組件。另外'view.controller.viewModel'會等於'this',這有什麼意義? – ZoolWay

+0

沒有仔細閱讀問題,檢查了您的使用情況,可以看到您想要的內容不會被'@ children'支持。也許有消息 – bigopon

1

我不知道這是否是你想要的,但你可以使用view-model.ref。例如:

<less-comp text="item three, containerless" view-model.ref="test"></less-comp> 

用法:

export class App { 
    attached() { 
    console.log(this.test); 
    } 
} 
+0

這種方式'less-comp'虛擬機在應用程序中可用,但它應該在'list-comp'(我當前輸出那些控制檯日誌)中。如果我用'repeat.for'編寫'less-comp',這個工作又會如何呢? – ZoolWay