如何在作用域插槽中获取refs元素

时间:2018-09-21 09:10:32

标签: vue.js vuejs2

如果插槽模板中有一些参考,如何从组件访问这些参考?例如:

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>
v-compoent.vue中的

this。$ refs.ele输出未定义。我的问题是如何获取该元素?

1 个答案:

答案 0 :(得分:0)

名为slotscopedSlot的每个元素都有context.$refs。 不要忘记先检查对象是否存在。

<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>

<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