[英]How to add components conditionally inside another component
我正在測試Knockout的組件功能,到目前為止,它已經能夠成功地在幾種情況下使用它。 現在,我遇到了一個找不到如何做的資源的方案。 我想基於某個關鍵字在另一個組件內添加一個組件。 這是一些片段:
父組件的模板
<div id="container">
</div>
父組件的視圖模型
define(["jquery", "knockout", "ko-postbox", "text!./parent.html"], function($, ko, kopost, template) {
function displayChildContent(value) {
switch (value.toLowerCase()) {
case "child":
//
// How to load child component?
//
break;
default:
break;
}
}
function ParentViewModel() {
ko.postbox.subscribe("child-click", function(newValue) {
displayChildContent(newValue);
}, this);
}
return { viewModel: ParentViewModel, template: template };
});
子組件的模板
<div>
<h1>Child</h1>
</div>
子組件的視圖模型
define(["text!./child.html"], function(template) {
function ChildViewModel() {
}
return { viewModel: ChildViewModel, template: template };
});
單擊已觸發,但我不知道如何在父模板中添加子模板。 另外,我計划使用自定義元素的參數綁定將一些數據從父級傳遞到子級。 將子模板添加到父模板后,它仍然可以這樣做嗎?
在您的父組件中添加類似於以下內容的行:
<!-- ko if: childTmpl --><!-- ko component: {name: 'child'} --><!-- /ko --><!-- /ko -->
其中childTmpl
是訂閱了child-click
的布爾型可觀察值。 現在,如果您不想在父級內部緊密耦合名為“ child”的組件,則可能會出現一個小問題。 在那種情況下,您仍然可以將其替換為父viewModel中的(n observable)屬性,甚至可以動態替換。 它將變成:
<!-- ko if: childTmpl --><!-- ko component: {name: childComp} --><!-- /ko --><!-- /ko -->
其中childComp
是一個屬性ParentViewModel
您可以通過PARAMS /定值/觀察到的填充。 以下是我測試過的示例模型:
function ParentViewModel(params) {
this.childComp = params && params.child || 'child';
this.childTmpl = ko.observable(true).subscribeTo("child-click");
}
function ChildViewModel(params) {
this.buttonClicked = ko.observable(true).publishOn("child-click");
}
ChildViewModel.prototype.toggle = function() {
this.buttonClicked(!this.buttonClicked());
};
在測試用例中,單擊子組件中的按鈕(最初顯示)將buttonClicked
觸發為false
,然后將childTmpl
也更新為false
,從而刪除子組件。 在這里查看完整的提琴:
http://jsfiddle.net/ohdodfzr/2/
至於第二個問題:
另外,我計划使用自定義元素的參數綁定將一些數據從父級傳遞到子級。
是的,您仍然可以這樣做。 您甚至可以通過父模板中的組件綁定傳遞整個父viewModel,例如:
<!-- ko component: {name: 'child', params: {parent: $data}} -->
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.