在 Vue 组件中改变渲染的 HTML 标签
Vary the Rendered HTML Tag in a Vue Component
我想知道是否可以让用户决定在 VueJS 组件中呈现哪个 html 标签。
例如,假设我们有 <my-component>Some Text</my-component>
。
我希望能够有一个名为 属性 的标签,它将确定呈现哪个 html 标签。因此,例如:
<my-component tag='a' href="http://some-url.com">Some Text</my-component>
将渲染到:
<a href="http://some-url.com">Some Text</my-component>
并且:
<my-component tag="div">Some Text</my-component>
将渲染到:
<div>Some Text</my-component>
h1-h6, p, span
和其他标签依此类推。
有什么想法吗?
谢谢。
当然,您可以使用 the render function, using createElement
and $slots
做到这一点。你所描述的只是以一种有点奇怪的方式写 HTML,但你可以这样做:
new Vue({
el: '#app',
components: {
myComponent: {
props: ['tag', 'attributes'],
render(createElement) {
return createElement(this.tag || 'div', {attrs: this.attributes || {}}, this.$slots.default);
}
}
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.2/vue.min.js"></script>
<div id="app">
<my-component tag="h1">A header</my-component>
<my-component tag="a" :attributes="{href:'http://www.google.com'}">a link to google</my-component>
<my-component>Default is div</my-component>
</div>
我想知道是否可以让用户决定在 VueJS 组件中呈现哪个 html 标签。
例如,假设我们有 <my-component>Some Text</my-component>
。
我希望能够有一个名为 属性 的标签,它将确定呈现哪个 html 标签。因此,例如:
<my-component tag='a' href="http://some-url.com">Some Text</my-component>
将渲染到:
<a href="http://some-url.com">Some Text</my-component>
并且:
<my-component tag="div">Some Text</my-component>
将渲染到:
<div>Some Text</my-component>
h1-h6, p, span
和其他标签依此类推。
有什么想法吗?
谢谢。
当然,您可以使用 the render function, using createElement
and $slots
做到这一点。你所描述的只是以一种有点奇怪的方式写 HTML,但你可以这样做:
new Vue({
el: '#app',
components: {
myComponent: {
props: ['tag', 'attributes'],
render(createElement) {
return createElement(this.tag || 'div', {attrs: this.attributes || {}}, this.$slots.default);
}
}
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.2/vue.min.js"></script>
<div id="app">
<my-component tag="h1">A header</my-component>
<my-component tag="a" :attributes="{href:'http://www.google.com'}">a link to google</my-component>
<my-component>Default is div</my-component>
</div>