原文地址: Vue: Pass Slots through from Parent to Child Componentsjavascript
有A、B、C三个component,分别包含不一样的slot:前端
const A = {
template: `<div><slot name="a">Default A Content</slot></div>`
}
const B = {
template: `<div><slot name="b">Default B Content</slot></div>`
}
const C = {
template: `<div><slot name="c">Default C Content</slot></div>`
}
复制代码
还有一个wrapper component W,代码以下:vue
Vue.component('W', {
props: ['child'],
template: `<component :is="child" />`
})
复制代码
A
, B
, C
会传入W,但问题是W并不知道A
, B
, C
会用哪一个slot。java
若是你尝试着这样写,react
<W :child="A">
<div slot="a">Special A Content</div>
</W>
复制代码
输出的结果确是Default A Content
, 缘由是slot a被当成了W的slot,而不是A的slot。git
因此咱们须要想办法,将传给W的slot,接着传下去,让子的component可以接收到。程序员
代码以下:github
Vue.component('W', {
props: ['child'],
template: `<component :is="child"> <slot v-for="(_, name) in $slots" :name="name" :slot="name" /> </component>`
})
复制代码
但上述代码还有一个小问题,就是不能识别scope slot中定义的变量,好比vuex
const D = {
template: `<div><slot name="d" emoji="🎉">Default D Content</slot></div>`
}
复制代码
其中的emoji就不能被slot中的代码识别。redux
解决的方法也是会者不难。
<template v-for="(_, name) in $scopedSlots" :slot="name" slot-scope="slotData"><slot :name="name" v-bind="slotData" /></template>
复制代码
因而,最终完整版的代码以下:
Vue.component('W', {
props: ['child'],
template: ` <component :is="child"> <slot v-for="(_, name) in $slots" :name="name" :slot="name" /> <template v-for="(_, name) in $scopedSlots" :slot="name" slot-scope="slotData"> <slot :name="name" v-bind="slotData" /> </template> </component>`
})
复制代码
新工做入职后,暂时没有前端程序员,只能本身琢磨着写起来,还好两年前本身的前端底子还在,vue上手也是快。
用vue写了快了两周的prototype后,真心以为vue+vuex比react+redux好上手多了。虽然一开始仍是没有从angular双向绑定的思路转变过来,很不习惯,但上手了之后发现,有了vuex这都不是事,真心好用!
借着眼下边摸索边作项目机会,也想顺手整理一下本身学到知识和技巧。因而,就从翻译这篇文章开始。
一些经常使用的code sheet会陆续整理到vue code snippet。