Knockout 3.2:组件/自定义元素可以包含子内容吗?

时间:2014-11-23 11:45:14

标签: knockout.js knockout-components

我可以创建在其中使用子标记的非空Knockout组件吗?

示例是用于显示模态对话框的组件,例如:

<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>

1 个答案:

答案 0 :(得分:6)

3.2中不可能,但是在下一版本中可以使用,this committest

目前您必须通过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>

请参阅fiddle

在新版本中,您可以使用$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。您可以手动构建最后一个版本的knockout以使用上面的代码。