2017-05-08 8 views
0

VueJSコンポーネントでどのhtmlタグをレンダリングするかをユーザーが決定できるかどうかは疑問です。VueコンポーネントでレンダリングされたHTMLタグを変更する

例えば、<my-component>Some Text</my-component>があるとします。

どのhtmlタグがレンダリングされるかを決定するタグと呼ばれるプロパティを持つことができます。したがって、たとえば:

<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および他のための

<my-component tag='a' href="http://some-url.com">Some Text</my-component> 

はにレンダリングされますタグ。

アイデア?

ありがとうございました。

答えて

1

確かに、それはcreateElement$slotsを使用してthe render functionで行うことができます。あなたがここで少しだけ奇妙な方法で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

関連する問題