Vue3 如何在组合式 api 中获取循环中的组件的 Ref
本文将介绍 Vue 3 中如何在组合式 API 中获取循环中的组件的 ref。我们将通过在父组件中使用 ref 指令和 v-for 指令来声明和动态创建一个引用,然后在 onMounted 生命周期钩子中循环遍历数据来获取每个子组件的引用并存储在对应的引用中。这种方法可以让我们轻松地在循环中获取子组件的引用并进行操作,非常方便实用。 基本用法 在 Vue 3 中,可以使用 ref 和 v-for 指令来在循环中获取组件的引用。 首先,在组件中,使用 ref 指令来声明一个引用: <template> <div ref="myComponent"></div> </template> 然后,在包含循环的父组件中,可以使用 v-for 指令来遍历数据并在循环中获取子组件的引用: <template> <div v-for="item in items" :key="item.id"> <my-component ref="myComponentRefs[item.id]"></my-component> </div> </template> <script> import { ref, onMounted } from "vue"; export default { setup() { const myComponentRefs = ref({}); const items = [{ id: 1 }, { id: 2 }, { id: 3 }]; onMounted(() => { items.forEach(item => { myComponentRefs.value[item.id] = myComponentRefs.value[item.id].$refs.myComponent; }); }); return { items, myComponentRefs, }; }, }; </script> 上面的例子中,使用 ref 指令在父组件中声明了一个名为 myComponentRefs 的引用。然后,在循环中,使用 myComponentRefs[item.id] 来动态创建一个引用来存储子组件的引用。在 onMounted 生命周期钩子中,通过循环遍历 items 数组来获取每个子组件的引用并存储在对应的引用中。 ...