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

2024-02-11

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

Outputs:

<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 中这是不可能的,但是在下一个版本中这是可能的,请参阅这次提交 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>

附:您可以手动构建最后版本的淘汰赛以使用上面的代码。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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