我能在Vue.js循环中使用插槽吗?

8

我有一个使用v-for循环的模板。在模板中,我有一个具有动态分配名称的命名插槽。没有任何内容显示,我做错了什么?

<todo-tabs :list="items">
    <div slot="interview">Interview</div>
    <div slot="membership">Membership</div>
    <div slot="profile">Profile</div>
    <div slot="handoff">Handoff</div>
</todo-tabs>

<template id="todo-tabs">
            <div class="tab-content ">      
                <div v-for="item in list" :class="{'active': item.current}" class="tab-pane" id="@{{ item.id }}">
                    <div class="skin skin-square">
                    <form class="form-horizontal" role="form">
                    <div class="form-body">
                        <slot name="@{{ item.id }}"></slot>
                    </div>
                    <div class="form-actions">
                        <button type="submit" class="btn red btn-outline">Submit</button>
                        <button type="button" class="btn default">Cancel</button>
                    </div>
                    </form>
                    </div>
                </div>
            </div>
        </template>

<script>
Vue.component('todo-tabs', {
        template: '#todo-tabs',
        props: ['list']
 });
 var vm = new Vue({
el: "#todo",
data: {
items : [
            {id: 'interview', name: 'interview', complete: true, body: 'something1', step_content: 'SOME'  },
            {id: 'membership', name: 'membership', complete: false, body: 'something2', step_content: 'SOME' },
            {id: 'profile', name: 'profile', complete: false, body: 'something3', step_content: 'SOME', current: true  },
            {id: 'handoff', name: 'handoff', complete: false, body: 'something4', step_content: 'SOME'}
        ]
    }
});
</script>
4个回答

20

在VueJs 2.1.3版本中,您可以使用以下代码:

parent:

<div v-for="row in rows">
    <slot name="buttons" :row="row"></slot>
</div>

孩子:

<template slot="buttons" scope="props">
    <a href="props.row.href">go there</a>
</template>

这个结构不会生成任何警告,因此我认为它是有效的。

https://v2.vuejs.org/v2/guide/components.html#Scoped-Slots


谢谢你! - jonan.pineda
非常好的回答。谢谢! - Jonatas Walker
1
在2.5.0+版本中,插槽作用域不再局限于<template>元素,而是可以在插槽中的任何元素或组件上使用。 - sknight

3
在VueJS 1.0.16中,您可以在模板中这样做:
<div v-for="item in tiems">
    <slot :name="item.id"></slot>
</div>

然而,从1.0.17版本开始,VueJS会抛出以下错误:<slot :name="item.id">:插槽名不能是动态的。

1
他其实改变了对此的想法。现在在1.0.18版本中是允许的。 - Bill Criswell
2
哈哈,我刚重新设计了一个组件以适应这个变化...但愿他不会在1.0.19版本再次改变主意。 - ierdna
感谢您的反馈。 - jhodgson4

0

可能值得与Evan(VueJS的创建者)讨论,但我认为slotname属性不是响应式的。我相信它只被视为字面量,并在模板编译之前进行评估。


0
当然,作为Vue 3,你可以使用动态插槽名称

parent.vue

<template v-for="row in rows" :key="row.id" #[`example-${row.id}`]></template>

child.vue

<template v-for="row in rows" :key="row.id">
            <slot :name="`example-${row.id}`"></slot>
</template>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接