2017-05-08 38 views
0

我想知道是否有可能允許用戶決定在VueJS組件中呈現哪個html標記。改變Vue組件中的呈現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等標籤。

任何想法?

謝謝。

回答

1

當然,你可以用the render function,使用createElement$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>

+0

感謝您的幫助。 – Moshe