我想从父级获取 vue.js 组件的尺寸(我正在使用实验性的 script setup )。
当我在组件内使用 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
inside the child component 的方法这种方法是否不起作用,因为引用作为 rfcs description says 是“默认关闭的”?
最佳答案
您可以使用 $el
字段访问根元素,例如:
<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.$el.getBoundingClientRect()
console.log(rect)
})
</script
关于vue.js - 无法在 vue 3 组合 api 中的组件上使用模板引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67033933/