无法在vue3组合api中的组件上使用模板引用

我想从父级获取 vue.js 组件的尺寸(我正在使用实验性脚本设置)。

当我在组件内使用 ref 时,它按预期工作。我得到尺寸:

// Child.vue
<template>
  <div ref="wrapper">
   // content ...
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'

const wrapper = ref(null)

onMounted(() => {
  const rect = wrapper.value.getBoundingClientRect()
  console.log(rect) // works fine!
})
</script>

但我想获取父组件内的维度。这可能吗?

我试过这个:

// Parent.vue
<template>
  <Child ref="wrapper" />
</template>
<script setup>
import Child from './Child'
import { ref, onMounted } from 'vue'

const wrapper = ref(null)

onMounted(() => {
  const rect = wrapper.value.getBoundingClientRect()
  console.log(rect) // failed!
})
</script>

控制台记录此错误消息:
Uncaught (in promise) TypeError: x.value.getBoundingClientRect is not a function


在文档中我只能找到在子组件中使用的方法template refs

这种方法是否不起作用,因为 refs 是“默认关闭的”,正如rfcs 描述所说的那样?

以上是无法在vue3组合api中的组件上使用模板引用的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>