看看这个场景:
ko.components.register('hello', {
viewModel: function() { },
template: "<h1>hello wrold</h1>"
});
如果我使用 <hello></hello>
生成的 html 结果将是:
<hello><h1>hello world</h1></hello>
但是如果我想要这个怎么办:
<hello class="hello"><h1>hello world</h1></hello>
那我怎样才能在组件中获取对自定义元素标签的引用呢?
最佳答案
自定义元素包含组件,它不被视为组件的一部分。就像在 foreach
、template
或 with
绑定(bind)中使用的外部标记一样。如果你想为该标签设置样式,你必须添加绑定(bind)来设置它的样式。该组件将填充其内容。
<hello data-bind="css: 'hello'"></hello>
但是,如果您绝对想访问父元素,我想这是可能的,但我不推荐这样做。组件应该只关心它自己,而不是包含它的容器。如果元素有任何也有绑定(bind)的子节点,这可能(并且将会)导致问题。
为您的 View 模型使用工厂函数。它将有权访问组件的信息(目前仅包括包含元素 element
)
ko.components.register('hello', {
viewModel: {
createViewModel: function (params, componentInfo) {
var element = componentInfo.element;
ko.applyBindingsToNode(element, { css: 'hello' });
return {};
}
},
template: "<h1>hello world</h1>"
});
关于javascript - 如何访问 Knockout 组件中的自定义元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25824030/