我想创建一个模板,例如
<{{ headerType }}>{{ text }}</{{ headerType }}>
并绑定数据
{
headerType: 'h3', // or h1, h2...
text: 'Header text'
}
生成的模板不会呈现为HTML,因此我最终会在页面上显示<h3>Header text</h3>
。
有这种方法吗?
答案 0 :(得分:4)
您可以使用具有渲染功能的组件。
Vue.component('heading', {
props: {
level: { type: String, required: true }
},
render: function (createElement) {
return createElement(
'h' + this.level, // tag name
this.$slots.default // array of children
)
},
});
var app = new Vue({
el: '#app',
data: {
level: "1",
text: 'hi'
}
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<select v-model="level"><option>1</option><option>2</option><option>3</option></select>
<heading :level="level">
{{text}}
</heading>
</div>
答案 1 :(得分:0)
你可以这样做:
<div id="demo">
<div v-html="'<' + headerType +'>' + text + '</' + headerType + '>'"></div>
</div>
为了更好的可读性,您可以将此字符串创建部分移动到单独的方法或计算属性中。
查看工作小提琴here。