Knockout 3.2: can components / custom elements con

2019-04-12 06:44发布

Can I create non-empty Knockout components that use the child markup within them?

An example would be a component for displaying a modal dialog, such as:

<modal-dialog>
  <h1>Are you sure you want to quit?</h1>
  <p>All unsaved changes will be lost</p>
</modal-dialog>

Which together with the component template:

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

1条回答
欢心
2楼-- · 2019-04-12 07:20

It's impossible in 3.2, however it would be possible in next version, see this commit and this test.

For now to you have to pass parameters to component via params property Define your component to expect content parameter:

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>'
});

Pass content parameter via params property

<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

In new version you can use $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. You can build last version of knockout manually to use code above.

查看更多
登录 后发表回答