在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>
发布于 2017-08-04 01:28:29
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/vue@2.2.6/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>
https://stackoverflow.com/questions/45490809
复制相似问题