我想创建一个模板,例如
<{{ headerType }}>{{ text }}</{{ headerType }}>并绑定数据
{
headerType: 'h3', // or h1, h2...
text: 'Header text'
}生成的模板不会呈现为HTML,因此我最终会在页面上使用<h3>Header text</h3>作为文本。
有这么好的方法吗?
发布于 2016-11-30 10:03:27
可以使用带有呈现函数的组件。
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>
发布于 2016-11-30 09:59:47
你可以这样做:
<div id="demo">
<div v-html="'<' + headerType +'>' + text + '</' + headerType + '>'"></div>
</div>您也可以在单独的方法或计算属性中移动此字符串创建部分,以获得更好的可读性。
见工作小提琴这里。
https://stackoverflow.com/questions/40884825
复制相似问题