ChenLee
ChenLee

Reputation: 1499

How to get refs element in scoped slot

If there are some refs in slot's template, how can I access these refs from the component? For example:

v-component.vue

<template>
    <div>
        <slot></slot>
    </div>
</template>
<script>
   export default {
       created() {
           console.log(this.$refs.ele)
       }
   }
</script>

app.vue

<template>
    <v-component>
       <template slot-scope="props">
          <h1 ref="ele"></h1>
       </template>
    </v-component>
</template>
<script>
   import VComponent from './v-component
   export default {
       components: { VComponent }
   }
</script>

this.$refs.ele in v-compoent.vue output undefined. My question is how can I get this element?

Upvotes: 11

Views: 25456

Answers (3)

Mysterdev
Mysterdev

Reputation: 259

On Vue 2 you can do this on mounted

  mounted() {
    console.log(this.$slots)
  },

with more precision

You can do this

  mounted() {
    console.log(this.$slots.name_of_your_slot)
  },

Upvotes: 1

Jean Claveau
Jean Claveau

Reputation: 1471

This is considered as a bad idea by Vue developers: https://github.com/vuejs/vue/issues/7661

Btw, in my case in Vue3, the el entries of my slots retrieved by

this.$refs.myRef.$slots['my-slot']().el

is always null (as appContext)

Upvotes: 3

doubleui
doubleui

Reputation: 556

Each element in named slot and scopedSlot has context.$refs. Do not forget to check if object exists first.

<template>
    <v-component>
        <template slot-scope="props">
            <h1 ref="ele">{{ props }}</h1>
        </template>
    </v-component>
</template>
<script>
import VComponent from './v-component'
export default {
    components: { VComponent }
}
</script>

and

<template>
    <div>
        <slot demo="foo"></slot>
    </div>
</template>
<script>
export default {
    created() {
        this.$nextTick(function() { // lazy
            console.warn(this.$scopedSlots.default()[0].context.$refs)
        });
    }
}
</script>

Result:

result

Upvotes: 9

Related Questions