【问题标题】:Vue3 composition API - accessing child refVue3 组合 API - 访问子引用
【发布时间】:2022-11-24 00:05:33
【问题描述】:

我正在尝试使用 Vue3 组合 API 访问子组件中的 ref,但我不确定该怎么做。我想向 mainContentRef 添加一个滚动事件,这样我就可以执行获取请求以在父组件中获取更多数据,但我似乎无法访问父组件中的 ref 以向其添加事件侦听器

这是我的代码(由于本示例不需要,因此删除了一些部分):

<!-- MAIN COMPONENT -->
<template>
    <PageWrap>
        <template v-slot:content>
            <MainContent>
                <template v-slot:content />
            </MainContent>
        </template>
    </PageWrap>
</template>

<script setup>

//access mainContentRef here because this is where the fetch request will be

</script>


<!-- MAIN CONTENT COMPONENT -->
<template>
    <div id="main-content" ref='mainContentRef'>
        <slot name='content'></slot>
    </div>
</template>

<script setup>

    import { defineProps, ref } from 'vue';

    const mainContentRef = ref(0);

</script>

【问题讨论】:

    标签: javascript vuejs3 vue-composition-api


    【解决方案1】:

    您可以使用 vue 的 defineExpose 方法,然后为您的 MainContent 组件添加一个 ref 并通过它访问它。

    <!-- MAIN COMPONENT -->
    <template>
        <PageWrap>
            <template v-slot:content>
                <MainContent ref="mainContentComponent">
                    <template v-slot:content />
                </MainContent>
            </template>
        </PageWrap>
    </template>
    
    <script setup>
        const mainContentComponent = ref()
        
        // Now you can do:
        mainContentComponent.value.mainContentRef.value
    </script>
    
    
    <!-- MAIN CONTENT COMPONENT -->
    <template>
        <div id="main-content" ref="mainContentRef">
            <slot name='content'></slot>
        </div>
    </template>
    
    <script setup>
        import { ref } from 'vue'
        
        const mainContentRef = ref(0)
        
        defineExpose({
            mainContentRef
        })
    </script>
    

    另见:https://vuejs.org/guide/essentials/template-refs.html#ref-on-component

    如果您有任何问题或它不起作用,请告诉我,很乐意提供帮助!

    【讨论】:

    • 哇哦,我不知道你能做到!我会尝试 defineExpose 方法,因为我没有遇到过这个!我会尝试实施它,看看效果如何!谢谢您的帮助!
    • 在主要内容组件中使用 define exposed 并在子组件上使用 ref 创造奇迹!我已经成功注销了 div,它现在(希望)允许我将我的事件监听器附加到它上面!谢谢!
    • 您使用defineExpose 但导入defineProps,这是故意的还是错误的?
    【解决方案2】:

    你可以试试:

    <!-- MAIN CONTENT COMPONENT -->
    <template>
        <div id="main-content" ref='mainContentRef'>
            <slot name='content'></slot>
        </div>
    </template>
    
    <script setup>
    
        import { defineProps, ref } from 'vue';
    
        const mainContentRef = ref(null);
    
         // Now you can do:
         mainContentRef.value.children[0]
    
    </script>
    

    【讨论】:

      猜你喜欢
      • 2023-01-13
      • 2021-09-16
      • 2021-03-05
      • 2021-05-22
      • 2021-02-23
      • 2022-11-09
      • 2021-06-25
      • 2021-06-11
      • 2022-12-22
      相关资源
      最近更新 更多