2017-08-03 36 views
0

是否可以將HTML標記(元素)綁定到Vue 2中的數據或屬性的值?將HTML標記綁定到數據或道具

我嘗試了不同的語法,但無法得到任何工作,谷歌搜索沒有幫助。

這裏有兩個我試過的語法:

直接 '串' 插補:

<{{ 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 > 

如果這是不可能的,我如何避免重複元素的內容和屬性來改變關聯的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

相關問題