淘汰赛3.2:组件/自定义元素可以包含子内容吗? [英] Knockout 3.2: can components / custom elements contain child content?
问题描述
我可以创建在其中使用子标记的非空Knockout组件吗?
Can I create non-empty Knockout components that use the child markup within them?
一个示例是用于显示模式对话框的组件,例如:
An example would be a component for displaying a modal dialog, such as:
<modal-dialog>
<h1>Are you sure you want to quit?</h1>
<p>All unsaved changes will be lost</p>
</modal-dialog>
与组件模板一起
<div class="modal">
<header>
<button>X</button>
</header>
<section>
<!-- component child content somehow goes here -->
</section>
<footer>
<button>Cancel</button>
<button>Confirm</button>
</footer>
</div>
输出:
<div class="modal">
<header>
<button>X</button>
</header>
<section>
<h1>Are you sure you want to quit?</h1>
<p>All unsaved changes will be lost</p>
</section>
<footer>
<button>Cancel</button>
<button>Confirm</button>
</footer>
</div>
推荐答案
在3.2中是不可能的,但是在下一版本中是可能的,请参见.
It's impossible in 3.2, however it would be possible in next version, see this commit and this test.
现在,您必须通过params
属性将参数传递给组件
定义您的组件以使用content
参数:
For now to you have to pass parameters to component via params
property
Define your component to expect content
parameter:
ko.components.register('modal-dialog', {
viewModel: function(params) {
this.content = ko.observable(params && params.content || '');
},
template:
'<div class="modal">' +
'<header>' +
'<button>X</button>' +
'</header>' +
'<section data-bind="html: content" />' +
'<footer>' +
'<button>Cancel</button>' +
'<button>Confirm</button>' +
'</footer>' +
'</div>'
});
通过params
属性传递内容参数
<modal-dialog params='content: "<h1>Are you sure you want to quit?</h1> <p>All unsaved changes will be lost</p>"'>
</modal-dialog>
请参见小提琴
在新版本中,您可以使用$componentTemplateNodes
In new version you can use $componentTemplateNodes
ko.components.register('modal-dialog', {
template:
'<div class="modal">' +
'<header>' +
'<button>X</button>' +
'</header>' +
'<section data-bind="template: { nodes: $componentTemplateNodes }" />' +
'<footer>' +
'<button>Cancel</button>' +
'<button>Confirm</button>' +
'</footer>' +
'</div>'
});
P.S.您可以手动构建最新版本的基因剔除,以使用上面的代码.
P.S. You can build last version of knockout manually to use code above.
这篇关于淘汰赛3.2:组件/自定义元素可以包含子内容吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!