在 3.2 中这是不可能的,但是在下一个版本中这是可能的,请参阅这次提交 https://github.com/knockout/knockout/commit/58dec530bdc27942c80f531700e611edfb9706fd和这个test https://github.com/knockout/knockout/blob/348f9eab6cab5e253d1d663c7b9ed1dcb692206d/spec/components/componentBindingBehaviors.js#L174.
现在您必须通过以下方式将参数传递给组件params
财产
定义您期望的组件content
范围:
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>
See fiddle http://jsfiddle.net/h1k4ujoh/2/
在新版本中您可以使用$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>'
});
在父组件中的用法:
<modal-dialog><div>This div is displayed in the <section> element of the modal-dialog</div>
</modal-dialog>
附:您可以手动构建最后版本的淘汰赛以使用上面的代码。