我正在使用 Vuejs。我创建了两个组件:First
和Second
.
First
呈现Second
.Second
有一个命名槽。First
包含一个<template>
, 进入Second
的命名槽。- 在
First
's<template>
- 还有另一个命名的插槽。 - 在
Second
's内部<slot>
- 有一个<template>
, 进入First
's<template>
的命名槽。
我得到的是First
'在' 插槽<template>
内渲染。Second
这是正确的,但我也希望看到Second
'在of中<template>
呈现。但我没有。<slot>
First
<template>
这是代码:
var First = Vue.extend({
template: `
<div>
In first<br/>
<second>
<template slot="slot1">
In template of First
<slot name="slot2">
</slot>
</template>
</second>
</div>
`
})
Vue.component('first', First)
var Second = Vue.extend({
template: `
<div>
In second<br/>
<slot name="slot1">
<template slot="slot2">
In template of Second
</template>
</slot>
</div>
`
})
Vue.component('second', Second)
这是输出:
In first
In second
In template of First
这是 jsfiddle:https ://jsfiddle.net/obeobe/f98kr4ye/
我想得到这个输出:
In first
In second
In template of First
In template of Second
我可以通过插槽实现这一点吗?如果没有,是否可以通过另一种方式实现,但不创建第三个组件?
编辑:一个可能的现实用例:一个 List 组件,它允许每个项目的 HTML 内容由其主机定义,并且可以在主机指定的位置将其自己的一些内容注入到主机的内容中。
例如,像这样:
主机组件:
<div class="myList">
<list v-bind:items="usersArray">
<template slot="itemSlot" slotScope="item">
<div>{{ item.name }}</div>
<div>{{ item.country }}</div>
<div>{{ item.phone }}</div>
<slot name="actions"> <--------- the spot for the List component to inject generic actions
</slot>
<div>{{ item.age }}</div>
</template>
</list>
</div>
“列表”组件:
<div>
<div v-for="(anItem, idx) in items">
<div>{{ idx }}</div>
<slot name="itemSlot" v-bind:item="anItem">
<template slot="actions">
<a v-on:click="duplicateItem(anItem)">Duplicate</a> <---------- the "duplicateItem" method would be implemented inside this List component
<a>Edit</a>
<a>Delete</a>
</template>
</slot>
</div>
</div>