vue.js - 如何在作用域插槽中获取 refs 元素

标签 vue.js vuejs2

如果插槽的模板中有一些引用,我如何从组件访问这些引用?例如:

v-component.vue

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

应用程序
<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-component.vue 输出中的 this.$refs.ele 未定义。我的问题是我怎样才能得到这个元素?

最佳答案

命名 slot 中的每个元素和 scopedSlotcontext.$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

关于vue.js - 如何在作用域插槽中获取 refs 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52440368/

相关文章:

javascript - Vue - 强制重新渲染所有组件

javascript - this.$data.randomData 和 this.randomData 有什么区别

vue.js - 有条件地渲染指令

javascript - Vue 变量值在请求后不更新

vue.js - 具有外部模板和样式的 Vue 组件?

javascript - v-on :click and event triggering on inner elements

javascript - 停止检查 alpineJS 中的复选框?

vue.js - 在 VueJS 组件中导入使用 getElementById 的模块

javascript - 添加另一个网站作为 serverMiddleware 的 Nuxt 模块

javascript - Vuex + vue 在使用字典作为状态对象时没有反应