【问题标题】:Refs methods in vue-composition-apivue-composition-api 中的 Refs 方法
【发布时间】:2022-01-19 15:28:30
【问题描述】:

有一个组件的引用是这样的:

<template>
  <custom-component
     ref="func"
  />
</template>

<script setup>
const func = ref();
</script>

在组件内部有这样一个函数:

const helloWorld = () => {
    console.log('hello World');
}

如何从父组件获得对 helloWorld 函数的访问权限?

【问题讨论】:

    标签: typescript vue.js vuejs3 vue-composition-api


    【解决方案1】:

    假设您的子组件也使用&lt;script setup&gt;,则组件的定义默认是关闭的(不公开)。

    您可以在子组件中手动公开带有defineExpose的方法:

    // CustomComponent.vue
    <script setup>
    const helloWorld = /*...*/
    
    defineExpose({
      helloWorld
    })
    </script>
    

    demo

    【讨论】:

    • 查看demo 和普通的ref
    • Vue 3 从vue 导出ref。另外,Vue 2 不支持&lt;script setup&gt;
    • @OmriCohen 支持 setup() 钩子,而不是 Vue 2 中模板的 &lt;script setup&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 2022-08-13
    • 2023-02-17
    • 2023-01-03
    • 2021-01-08
    • 2020-06-16
    • 2021-04-26
    相关资源
    最近更新 更多