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

新手上路,请多包涵

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

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

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

如果我使用 Options 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 做到这一点?

原文由 Pavel_K 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 769
2 个回答

您需要在设置中创建 ref const 然后将其返回以便可以在 html 中使用。

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

import { ref, onMounted } from 'vue';

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

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

    return { table };
}

原文由 dantheman 发布,翻译遵循 CC BY-SA 4.0 许可协议

关于 Laravel 惯性:

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

// a list for testing
let items = [
  { id: 1, name: "item name 1" },
  { id: 2, name: "item name 2" },
  { id: 3, name: "item name 3" },
];

// this also works with a list of elements
let elements = ref(null);

// testing
onMounted(() => {

  let all = elements.value;
  let item1 = all[0];
  let item2 = all[1];
  let item3 = all[2];

  console.log([all, item1, item2, item3]);

});
</script>
<template>
  <div>

    <!-- elements -->
    <div v-for="(item, i) in items" ref="elements" :key="item.id">

      <!-- element's content -->
      <div>ID: {{ item.id }}</div>
      <div>Name: {{ item.name }}</div>

    </div>

  </div>
</template>

原文由 Jeferson G. Silva 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题