簡體   English   中英

在Vue組件中改變渲染的HTML標簽

[英]Vary the Rendered HTML Tag in a Vue Component

我想知道是否有可能允許用戶決定將在VueJS組件中呈現哪個html標簽。

例如,假設我們有<my-component>Some Text</my-component>

我希望能夠擁有一個稱為tag的屬性,該屬性將確定呈現哪個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類推h1-h6, p, span和其他標簽。

有任何想法嗎?

謝謝。

當然,您可以使用createElement$slots 的render函數來實現。 您所描述的只是以一種有點怪異的方式編寫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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM