【问题标题】:Knockout 3.2: can components / custom elements contain child content?Knockout 3.2:组件/自定义元素可以包含子内容吗?
【发布时间】:2023-03-26 19:50:01
【问题描述】:

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

【问题讨论】:

  • 看看淘汰赛 3.3 - 它有你想要的。

标签: knockout.js knockout-components


【解决方案1】:

这在 3.2 中是不可能的,但是在下一个版本中它是可能的,参见 this commit 和这个 test

现在你必须通过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>'
});

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

【讨论】:

  • 感谢您的回答,但这不是我想要的。我的目标是自然地使用标记子树,而不是使用基于参数的 hack。
  • @janfoeh 已编辑,请检查
  • 谢谢 Max,$componentTemplateNodes 正是我想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-19
  • 2012-08-21
  • 2014-10-26
  • 2017-07-08
  • 2017-04-24
  • 2010-09-17
相关资源
最近更新 更多