如何在 Vue3 中使用 Composition API 获取 $refs?

How to get $refs using Composition API in Vue3?

我正在尝试使用 Composition API 在 Vue 3 中获取 $refs。这是我的模板,它有两个子组件,我需要获取对一个子组件实例的引用:

<template>
    <comp-foo />
    <comp-bar ref="table"/>
</template>

在我的代码中,我使用 Template Refs: ref 是一个特殊属性,允许我们在挂载后获得对特定 DOM 元素或子组件实例的直接引用。

如果我使用选项 API 那么我没有任何问题:

  mounted() {
    console.log("Mounted - ok");
    console.log(this.$refs.table.temp());
  }

但是,使用 Composition API 我得到错误:

setup() {
    const that: any = getCurrentInstance();
    onMounted(() => {
      console.log("Mounted - ok");
      console.log(that.$refs.table.temp());//ERROR that.$refs is undefined
    });
    return {};
  }

谁能告诉我如何使用 Composition API?

您需要在设置中创建 ref const,然后 return 它才能在 html.

中使用
<template>
    <div ref="table"/>
</template>

import { ref, onMounted } from 'vue';

setup() {
    const table = ref(null);

    onMounted(() => {
      console.log(table.value);
    });

    return { table };
}
<template>
    <your-table ref="table"/>
    ...
</template>

<script>
import { ref, onMounted } from 'vue';

setup() {
    const table = ref(null);

    onMounted(() => {
      table.value.addEventListener('click', () => console.log("Event happened"))
    });

    return { table };
}
</script>

在你的其他组件中,你可以与你已经在 onMounted 生命周期挂钩上注册的事件进行交互,就像我的例子一样,我只注册了一个 evnet

如果你愿意,你可以在父组件中使用getCurrentInstance()像这样的代码:

<template>
    <MyCompo ref="table"></MyCompo>
</template>

<script>
import MyCompo from "@/components/MyCompo.vue"
import { ref, onMounted, getCurrentInstance } from 'vue'
export default {
    components : {
        MyCompo
    },
    
    setup(props, ctx) {
        
        onMounted(() => {
          getCurrentInstance().ctx.$refs.table.tempMethod()
           
        });
    }
}
</script>

这是子组件的代码(这里我称之为MyCompo):

<template>
    <h1>this is MyCompo component</h1>
</template>

<script>
export default {
    
    setup(props, ctx) {
        
        const tempMethod = () => {
            console.log("temporary method");
        }

        return {
            tempMethod
        }
    },
}
</script>