knockout.js 淘汰赛3.2:组件/自定义元素可以包含子内容吗?

dy1byipe  于 7个月前  发布在  其他
关注(0)|答案(1)|浏览(66)

我可以创建使用子标记的非空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>
lg40wkob

lg40wkob1#

这在3.2中是不可能的,但在下一个版本中是可能的,请参阅this commit和此测试。
现在,你必须通过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>'
});

在父组件中的用法:

<modal-dialog><div>This div is displayed in the <section> element of the modal-dialog</div>
</modal-dialog>

P.S.您可以手动构建最后一个版本的淘汰赛,以使用上面的代码。

相关问题