Javascript 如何让父级了解插槽中的子组件?

Javascript 如何让父级了解插槽中的子组件?,javascript,vue.js,vuejs2,vue-component,Javascript,Vue.js,Vuejs2,Vue Component,我想知道如何让父组件知道插槽中的子组件 例如,如果我想创建一个滑块,并且我希望具有以下结构: 我认为: <vue-slider> <vue-slide name="First slide!">First slide content</vue-slide> <vue-slide name="Second slide!">Second slide content</vue-slide> </vue-slider>

我想知道如何让父组件知道插槽中的子组件

例如,如果我想创建一个滑块,并且我希望具有以下结构:

我认为:

<vue-slider>
    <vue-slide name="First slide!">First slide content</vue-slide>
    <vue-slide name="Second slide!">Second slide content</vue-slide>
</vue-slider>

第一张幻灯片内容
第二张幻灯片内容
VueSlider.vue

<template>
    <div class="slider">
        <ol>
            <li v-for="(slide,index) in slides">{{slide.name}}</li>
        </ol>


        <slot></slot>
    </div>
</template>

<script>
    export default {

        data: function(){
          return {
              slides: [],
          }
        }
    }
</script>

  • {{slide.name}
  • 导出默认值{ 数据:函数(){ 返回{ 幻灯片:[], } } }
    VueSlide.vue

    <template>
        <div class="slide">
            <slot></slot>
        </div>
    </template>
    
    <script>
        export default {
            props: {
                'name': {
    
                }
            }
        }
    </script>
    
    
    导出默认值{
    道具:{
    “姓名”:{
    }
    }
    }
    
    所以我想在父组件上填充幻灯片数组。我曾考虑在安装每张幻灯片时发出一个事件,但后来我在vue文档中读到:

    不能使用$on侦听子级发出的事件。必须在模板中直接使用v-on>,如下例所示


    谢谢

    默认插槽中的所有内容都可以通过
    $slots获得。组件中的默认插槽(命名插槽可以通过
    $slots[name]
    获得)。因此,如果要在父组件中填充
    幻灯片
    数组,可以检查默认插槽的内容并删除非幻灯片的节点(空格(如回车符)包含为节点)

    这里有一个例子

    console.clear()
    Vue.component(“VueSlider”{
    模板:`
    幻灯片数:{{slides.length}
    
  • {{slide.name}
  • `, 数据:函数(){ 返回{ 幻灯片:[], } }, 安装的(){ for(让此节点的节点$slots.default){ //过滤掉空白节点 如果(node.tag){ //可能需要选中此选项以仅添加VueSlide节点 this.slides.push(node.componentInstance) } } } }) Vue.component(“VueSlide”{ 模板:` `, 道具:{ “名称”:字符串 } }) 新Vue({ el:“应用程序” })
    
    第一张幻灯片内容
    第二张幻灯片内容
    
    非常感谢您的详细回复。正是我要找的!