【发布时间】:2017-06-04 13:46:11
【问题描述】:
如何制作类似于 vue-router router-link 的组件,通过 props 获取标签来呈现我的模板?
<my-component tag="ul">
</my-component>
将呈现:
<ul>
anything inside my-component
</ul>
【问题讨论】:
标签: vue.js vuejs2 vue-router
如何制作类似于 vue-router router-link 的组件,通过 props 获取标签来呈现我的模板?
<my-component tag="ul">
</my-component>
将呈现:
<ul>
anything inside my-component
</ul>
【问题讨论】:
标签: vue.js vuejs2 vue-router
您可以像这样使用内置的component 元素:
<component is="ul" class="foo" style="color:red">
anything inside component
</component>
见:https://vuejs.org/v2/guide/components.html#Dynamic-Components
【讨论】:
<component v-bind:is="nameOfPropOrComputedProperty">,这样做你可以通过prop在父模板中传递包装器标签名称。来源:https://vuejs.org/v2/guide/components.html#Dynamic-Components
编辑:请检查@krukid 答案,这是一个更好的解决方案,我回答时不知道component 元素
渲染函数方式:
您需要创建一个使用渲染功能的“包装器组件”。
import Vue from 'vue';
Vue.component('wrapper-component', {
name: 'wrapper-component',
render(createElement) {
return createElement(
this.tag, // tag name
this.$slots.default // array of children
);
},
props: {
tag: {
type: String,
required: true,
},
},
});
然后在任何其他模板中使用如下
<wrapper-component tag="div">
<span>All this will be rendered to inside a div</span>
<p>
All
</p>
</wrapper-component>
应该渲染到这个
<div>
<span data-v-4fcf631e="">All this will be rendered to inside a div</span>
<p data-v-4fcf631e="">
All
</p>
</div>
要了解更多关于渲染函数的信息,请参阅official documentation
【讨论】:
this.tag 在您的代码中不起作用,而 this.$props.tag 可以。