cas*_*ral 23 vue.js vue-router vuejs2
如何创建一个类似于vue-router的组件router-link,我通过props获取标签来呈现我的模板?
<my-component tag="ul">
</my-component>
Run Code Online (Sandbox Code Playgroud)
会呈现:
<ul>
anything inside my-component
</ul>
Run Code Online (Sandbox Code Playgroud)
kru*_*kid 71
你可以component像这样使用内置元素:
<component is="ul" class="foo" style="color:red">
anything inside component
</component>
Run Code Online (Sandbox Code Playgroud)
请参阅:https://vuejs.org/v2/guide/components.html#Dynamic-Components
Ald*_*o88 14
编辑:请检查@krukid答案,这是一个更好的解决方案,component当我回答时,我不知道元素
渲染功能方式:
您需要创建一个使用render函数的"包装器组件".
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,
},
},
});
Run Code Online (Sandbox Code Playgroud)
然后在任何其他模板中使用如下
<wrapper-component tag="div">
<span>All this will be rendered to inside a div</span>
<p>
All
</p>
</wrapper-component>
Run Code Online (Sandbox Code Playgroud)
这应该呈现给你
<div>
<span data-v-4fcf631e="">All this will be rendered to inside a div</span>
<p data-v-4fcf631e="">
All
</p>
</div>
Run Code Online (Sandbox Code Playgroud)
有关渲染功能的更多信息,请参阅官方文档