我有我的 app.js 来生成选项卡,如下所示:
输入:
<tabs>
<div>
<a slot="header">Tab 1</a>
<article slot="content">
<h2>Tab 1 Content</h2>
<p>Lorem ipsum dolor sit amet</p>
</article>
</div>
<div>
<a slot="header">Tab 2</a>
<article slot="content">
<h2>Tab 2 Content</h2>
<p>Sed ut perspiciatis unde</p>
</article>
</div>
<div>
<a slot="header">Tab 3</a>
<article slot="content">
<h2>Tab 3 Content</h2>
<p>Neque porro quisquam est</p>
</article>
</div>
</tabs>
上面的每个 div
指定一个 tab
。 header
槽是选项卡导航的标题,内容槽是各个选项卡的选项卡内容。
通过将上述输入添加到我的 tabs
组件中,我必须生成以下输出:
输出:
<section class="tabs">
<nav class="tabs-nav">
<ul class="tabs-list">
<li class="tabs-listitem">
<a class="tabs-trigger">Tab 1</a>
</li>
<li class="tabs-listitem">
<a class="tabs-trigger">Tab 2</a>
</li>
<li class="tabs-listitem">
<a class="tabs-trigger">Tab 3</a>
</li>
</ul>
</nav>
<div class="tabs-body">
<article>
<h2>Tab 1 Content</h2>
<p>Lorem ipsum dolor sit amet</p>
</article>
<article>
<h2>Tab 2 Content</h2>
<p>Sed ut perspiciatis unde</p>
</article>
<article>
<h2>Tab 3 Content</h2>
<p>Lorem ipsum dolor sit amet</p>
</article>
</div>
</section>
通过对选项卡的上述输入,我如何在渲染函数或 Vue 模板中获得上面指定的输出。
如果我尝试通过 this.$slots.header
迭代插槽,则会出现未定义
有人可以帮我实现这个目标吗
最佳答案
这是 Vue 中的基本循环。希望这有帮助
Vue.component('tabs', {
props: ['tabs'],
template: `
<section class="tabs">
<nav class="tabs-nav">
<ul class="tabs-list">
<li v-for="item in tabs" :key="item" class="tabs-listitem">
<a class="tabs-trigger">{{item.title}}</a>
</li>
</ul>
</nav>
<div class="tabs-body">
<article v-for="item in tabs" v-html="item.content" :key="item"></article>
</div>
</section>`
})
var app = new Vue({
el: '#app',
data () {
return {
tabs: [
{
title: 'Tab 1',
content: '<h1>Tab 1 Content</h1>'
},
{
title: 'Tab 2',
content: '<h1>Tab 2 Content</h1>'
},
{
title: 'Tab 3',
content: '<h1>Tab 3 Content</h1>'
}
]
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
<div id="app">
<tabs :tabs="tabs"></tabs>
</div>
关于javascript - Vue <template> 标记在迭代列表时未按预期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52685293/