Oli*_*der 5 web-component polymer polymer-2.x
我想使用<slot>插入点从父组件向子组件注入渲染模板.注入的模板包含子组件属性的数据绑定(my-child.data在本例中).
<dom-module id="my-parent">
<template>
<my-child>
<template>
<div>Child's data property: [[data]]</div>
</template>
</my-child>
</template>
...
Run Code Online (Sandbox Code Playgroud)
渲染子组件基本上如下所示:
<dom-module id="my-child">
<template>
<header></header>
<slot></slot>
<footer></footer>
</template>
<script>
class MyChild extends Polymer.Element {
static get is() { return 'my-child'; }
static get properties() {
return {
data: { ... }
};
}
...
Run Code Online (Sandbox Code Playgroud)
我不确定Polymer2是否可以实现这一点.Vue2有一个名为"范围槽"的概念来实现这一目标.提前感谢您的任何反馈!
默认情况下,数据绑定绑定在绑定的当前范围内.如果要更改范围,必须将标记放在标记内<template>并在其他范围内标记.
你问题中的HTML代码已经没问题了 - 你实际上将light DOM包装在一个内部<template>,但你却<template>错误地使用了它.您不能使用<slot>,但必须手动标记该模板并将其插入my-child元素的阴影DOM 内的某处.
在这里你有一个如何实现这个目标的工作演示:http://jsbin.com/loqecucaga/1/edit?html,console,output
我甚data至已经将属性绑定添加到input元素,以证明属性更改也会影响标记的模板.
冲压相对简单,并在connectedCallback方法内完成:
var template = this.querySelector('template');
this.__instance = this._stampTemplate(template);
this.$.content.appendChild(this.__instance);
Run Code Online (Sandbox Code Playgroud)
标记的模板放在占位符div元素中,您可以将其放在my-child模板中的某个位置:
<div id="content"></div>
Run Code Online (Sandbox Code Playgroud)
总结一下,这是演示的完整代码:
<link href="polymer/polymer-element.html" rel="import"/>
<link href="polymer/lib/mixins/template-stamp.html" rel="import"/>
<dom-module id="my-parent">
<template>
<my-child>
<template>
<div>Child's data property: [[data]]</div>
</template>
</my-child>
</template>
<script>
class MyParent extends Polymer.Element {
static get is() { return 'my-parent'; }
}
window.customElements.define(MyParent.is, MyParent);
</script>
</dom-module>
<dom-module id="my-child">
<template>
<header>Header</header>
<div id="content"></div>
<footer>Footer</footer>
<input type="text" value="{{data::input}}" />
</template>
<script>
class MyChild extends Polymer.TemplateStamp(Polymer.Element) {
static get is() { return 'my-child'; }
static get properties() {
return {
data: {
type: String,
value: 'Hello, World!'
},
};
}
connectedCallback() {
super.connectedCallback();
var template = this.querySelector('template');
this.__instance = this._stampTemplate(template);
this.$.content.appendChild(this.__instance);
}
}
window.customElements.define(MyChild.is, MyChild);
</script>
</dom-module>
<my-parent></my-parent>
Run Code Online (Sandbox Code Playgroud)