VueJS:在运行时跟踪父槽中子组件的顺序

问题描述 投票:0回答:1

我有一个自定义组件,其中父组件和子组件数组紧密耦合,并且使用 vue 提供的提供注入功能在父组件和子组件之间存在“后门”通信。

在父组件中,我想按照子组件在插槽中定义的顺序来跟踪子组件。

我知道在安装时,子组件会按照定义的顺序实例化。然而,在运行时,例如,子组件可能被插入到第一个子组件和第二个子组件之间。问题是如何找出父槽中子组件的更新顺序?

我在vue devtools中看到,它可以识别“组件”选项卡中子组件和嵌套组件的顺序,并以树形布局显示它。我怎样才能实现这样的目标?

vue.js vue-component
1个回答
0
投票

将槽作为对象数组传递,将内部元素内容作为对象内部的值传递。使用数组拼接添加新插槽。如果子组件元素较多,可以使用v-html或者其他方法

父组件

<template>
   <div>
     <slot></slot>
     <ul>
        <li v-for="(s,i) in slotsArray" :key="i">
            <slot :name="s.name"></slot>
        </li>
     </ul>
 </div>
</template>
<script>
  export default {
    props: {
      slotsArray: { type: Array, default: null }
    }
  };</script>

父组件使用和添加插槽

<template>
  <div>
     <!-- Parent Component -->
     <parent-component :slotsArray="slotsArray">
         <button @click="addSlotToIndex(2, 'Item 21')">Add Item on 2nd 
            Index</button>
         <button @click="addSlotToIndex(0, 'Item 00')">Add Item on 1st 
            Index</button>
         <template v-for="(s) in slotsArray">
             <template :slot="s.name">
                <p :key="s.i">{{s.child}}</p>
             </template>
         </template>
  </parent-component></div></template>

<script>
import ParentComponent from './views/parent-child- 
    slots/ParentComponent.vue';

export default {
    name: 'App',
    components: { ParentComponent },
    data () {
        return {
            slotsArray: [
                {
                    name: 'slota',
                    child: 'Item 1'
                },
                {
                    name: 'slotb',
                    child: 'Item 2'
                },
                {
                    name: 'slotc',
                    child: 'Item 3'
                }
            ],
            addSlotToIndex (idx, value) {
                this.slotsArray.splice(idx, 0, {
                    name: idx > 0 ? this.slotsArray[idx - 1].name + 'a' : 
                     this.slotsArray[0].name + 'a',
                   child: value
            });
        }
    };
}};
© www.soinside.com 2019 - 2024. All rights reserved.