Vue中如何根据prop动态为组件内容包裹指定HTML标签
实现方案
方案1:修改组件template(零侵入现有调用逻辑,适配你上百处调用无需修改的需求)
仅修改first-comp组件的模板部分,添加条件渲染即可,所有外部调用组件的代码无需任何改动:
const localComponent = { name:'first-comp', template:` <button v-if="wrappwithbutton"> <div> {{text}}</div> </button> <div v-else> {{text}}</div> `, props:['wrappwithbutton','text'], } const app = new Vue({ el:'#app', name:'app', components:{'first-comp':localComponent}, });
运行后完全匹配你的预期:
wrappwithbutton为true时,渲染结果为<button><div>press me i'm button</div></button>wrappwithbutton为false时,直接渲染<div>don't wrap me with button leave me as it is</div>
方案2:render函数实现(适配后续扩展需求)
如果后续需要动态更换包裹的标签类型,不用修改模板条件,用render函数扩展性更强:
const localComponent = { name:'first-comp', props:['wrappwithbutton','text', 'wrapTag'], // 新增wrapTag可自定义包裹标签,默认用button render(h) { const innerContent = h('div', this.text) if (this.wrappwithbutton) { return h(this.wrapTag || 'button', {}, [innerContent]) } return innerContent } }
内容的提问来源于stack exchange,提问作者EaBengaluru
相关产品推荐
相关产品推荐

