首页 > 解决方案 > 引用 vue 中的命名槽

问题描述

我有一个带有 2 个插槽(都已填充)的 vue 组件,我需要获取相对于页面的位置(getBoundingClientRect例如使用方法),但watchable即使使用refs. 有没有方法可以做到这一点this.$el.querySelector

<template>
    <div class="watchable-container">
        <slot name="watchable" ref="refWatchable"></slot>
        <div class="bubble-container">
            <div class="bubble">
                <slot name="content">

                </slot>
            </div>
            <div class="bubble-tail"></div>
        </div>
    </div>
</template>

<script>
export default {
    name: "BubblePopover",
    mounted() {
        console.log(this.$slots)
        console.log(this.$refs);
    },
}
</script>

标签: javascriptvue.jsvuejs2vue-component

解决方案


this.$slots成员应该工作。

this.$slots.watchable
// or
this.$slots.watchable.$el

尝试nextTick在您的挂载函数中使用,以给插槽时间进行渲染。

mounted() {
  nextTick(()=>{
     // your code here
  })
}

您还可以从您的插槽内容中添加一个 ID 添加访问权限getElementById

另一种选择是使用组合 API 插件,然后从 ref 访问内容。


推荐阅读