2017-08-03 9 views
0

HTMLタグ(要素)をVue 2のデータまたはプロパティの値にバインドすることは可能ですか?HTMLタグをデータまたは小道具にバインドする

私はさまざまな構文を試しましたが、動作することができず、グーグルが助けになりませんでした。

直接 'string' に補間::

<{{ someProp ? 'button' : 'a' }}> 
    <!-- Some complex template I want to keep DRY --> 
</{{ someProp ? 'button' : 'a' }}> 

V-バインドテンプレート要素にタグを(希望に満ち推測):

<template :tag="someProp ? 'button' : 'a'"> 
    <!-- Some complex template I want to keep DRY --> 
</template > 

は、ここで私が試したの構文の2つです

これが不可能な場合、関連するHTMLタグを変更するために要素のコンテンツと属性を複製することを避けるにはどうすればよいですか?私は避けたいことです:

<button v-if="someProp" /* Some attribute bindings */> 
    <!-- Some complex template I want to keep DRY --> 
</button> 
<a v-else /* Repeating the above attribute bindings */> 
    <!-- Repeating the above template, breaking the DRY principle --> 
</a> 

答えて

1

のVueの動的componentタグは、Vueのコンポーネントで動作するように意図されていますが、それは同様にHTMLタグで動作ありません。

<component :is="tag">Click me</component> 

ここは例です。

console.clear() 
 

 

 
new Vue({ 
 
    el:"#app", 
 
    data:{ 
 
    tag: "a", 
 
    }, 
 
    methods:{ 
 
    onClick(){ 
 
     alert('clicked') 
 
    }, 
 
    changeTag(){ 
 
     this.tag = this.tag == "a" ? "button" : "a" 
 
    } 
 
    } 
 
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script> 
 
<div id="app"> 
 
    <component :is="tag" @click="onClick" href="javascript:void(0)">Click me</component> 
 

 
    <hr> 
 
    <button @click="changeTag">Change tag</button> 
 
</div>

+0

まさに私が必要なもの、ありがとう! :) – Lazlo

関連する問題