Peter
Peter

Reputation: 69

Vue - Standard practice when accessing slots

Is the following an accepted standard practice when attempting to access slots?

    const slotElement = this.$slots['slot-name'][0].elm;
    const value = this.getSomething(slotElement);

Upvotes: 1

Views: 319

Answers (2)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85653

You can simply use the slot name.

this.$slots.slotName // named slot
this.$slots.default // default slot

Example from the api:

<blog-post>
  <h1 slot="header">
    About Me
  </h1>

  <p>Here's some page content, which will be included in vm.$slots.default, because it's not inside a named slot.</p>

  <p slot="footer">
    Copyright 2016 Evan You
  </p>

  <p>If I have some content down here, it will also be included in vm.$slots.default.</p>.
</blog-post>

Vue.component('blog-post', {
  render: function (createElement) {
    var header = this.$slots.header
    var body   = this.$slots.default
    var footer = this.$slots.footer
    return createElement('div', [
      createElement('header', header),
      createElement('main', body),
      createElement('footer', footer)
    ])
  }
})

Upvotes: 2

Stephen Thomas
Stephen Thomas

Reputation: 14063

As I noted in a comment, you can't count on a slot being filled with a single DOM element; the parent may be using a <template> to bundle multiple elements together. In that case, you wouldn't want the position of the first element in the slot.

An alternative approach would be to wrap your slot with a <div> element, define a reference to that <div>, and then access the reference's position:

<div ref="slotWrapper">
    <slot name="slot-name"/>
</div>

And then in your code:

rect = this.$refs.slotWrapper.getBoundingClientRect();

Upvotes: 0

Related Questions