javascriptvue.jsvue-loader

How to access content of slot in another child component


Following problem:

I have a Vue.js component which relies on its parent's DOM. But the moment the prop gets passed, it (this.$el) is undefined, probably because it's not yet mounted then.

My component's vue template file looks like this:

<template>
  <md-card>
    <md-card-content>
      <ol>
        <li v-for="item in headings(content)">
          <a :href="`#${item.id}`">{{ item.name }}</a>
        </li>
      </ol>
    </md-card-content>
  </md-card>
</template>
<script>
  export default {
    props: ['content'],
    methods: {
      headings(content) {
        // DOM element is used
        // At this moment, `content` is undefined
      },
    },
  };
</script>

The component that uses the one above includes this piece of code:

<article-index :content="this.$el"></article-index>

I thought of waiting for the parent component to be mounted, but that way I can't seem to keep the template like above, because it would always try to access the method (or variable) instantly.

How can I solve this?

Edit:

<template>
  <div class="content">
    <div class="left"><article-index :content="this.$el"></article-index></div>
    <div class="article"><slot></slot></div>
    <div class="right"><slot name="aside"></slot></div>
  </div>
</template>

Here's the parent component's template. The only thing I actually need is the .article div, or the slot's contents.


Solution

  • You can get it using this.$slots, in the parent component's mount function you can access this.$slots and assign it to some variable which can be passed to article-index component.

    Following code prints the passed slots:

    Vue.component('wrapper', {
        name: 'Wrapper',
      template: `<div><slot></slot></div>`,
      mounted () {
        this.$slots.default.forEach(vnode => { 
            console.log(vnode)
        })
      }
    })
    

    Sample fiddle here.