vue.js - Vuejs : Getting slot content componentInstances not rendered due to `v-if`

标签 vue.js

我想递归组合选项卡和 TreeView 。查看下面的简单示例以了解它的工作情况:

Vue.component('tabs', {
  template: '#tabs',
  data(){
    return {
      tabs:[],
      expanded:true,
    };
  },
  mounted(){
    for (i = 0; i < this.$slots.default.length; i++) {
      let tab = this.$slots.default[i];
      if (tab.componentOptions && tab.componentOptions.tag == 'tab') {
        this.tabs.push(tab.componentInstance);
      }
    }
  }
});

Vue.component('tab', {
  template: '#tab',
  props: ['label']
});

app = new Vue({
  'el': '#inst',
});
<!-- templates -->
<script type="text/x-template" id="tabs">
  <div @click.stop="expanded = !expanded">
    <h1><slot name="h" /></h1>
    <div v-if="expanded" class="children">
      <ul><li v-for="tab in tabs">{{tab.label}}</li></ul>
    <div style="border:1px solid #F00"><slot /></div>
  </div>
</script>
<script type="text/x-template" id="tab">
  <strong><slot /></strong>
</script>

<!-- data -->
<tabs id="inst">
  <div slot="h">Woot</div>
  <tab label="label">
    <tabs>
      <div slot="h">Weet</div>
      <tab label="sub">Weetley</tab>
  </tab>
  <tab label="label2">Woot3</tab>
</tabs>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.min.js"></script>

现在我有了带有单独标签的选项卡,我可以向选项卡添加一些事件状态并完成。

除了为了获取选项卡以便我可以遍历它们以在父级中制作标签外,我循环遍历 this.$slots.default 以查找选项卡。问题是,当我将扩展默认值更改为 false 时,v-if 触发并且 componentInstance 永远不会被填充。

我不想使用 v-show 因为使用 vue 的全部原因是为了抵消巨大的 DOM 和显示的性能损失(这是以前实现的方式)。如何将我的子组件放入我的数据中?

最佳答案

所以你需要它开始扩展,并且在 mounted 运行后,将扩展设置为它的预期初始值:

Vue.component('tabs', {
  template: '#tabs',
  data() {
    return {
      tabs: [],
      defaultExpanded: false,
      expanded: true,
    };
  },
  mounted() {
    for (const tab of this.$slots.default) {
      if (tab.componentOptions && tab.componentOptions.tag == 'tab') {
        this.tabs.push(tab.componentInstance);
      }
    }
    this.expanded = this.defaultExpanded;
  }
});

关于vue.js - Vuejs : Getting slot content componentInstances not rendered due to `v-if` ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44141351/

相关文章:

vue.js - Vue 3 Composition API 在多个组件中重用

vue.js - 如何将操作按钮添加到数据表?

javascript - Vim:如何从行首计算缩进

javascript - 如何在Vue中提交表单,重定向到新路由并传递参数?

具有多个应用程序的 Django + Vue

jquery - VueJS jQuery : computed value of parent data attribute undefined

javascript - bootstrap-vue.js 与 laravel 未知的自定义元素 : <b-alert> error

web - 我如何根据 Vuetify 中的屏幕大小更改按钮的位置

javascript - 如何使用 javascript 中的坐标突出显示字符串中的单词?

javascript - 为axios调用绑定(bind)数据到vue