【发布时间】:2021-07-06 02:11:06
【问题描述】:
我想从父级获取 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 refsinside the child component的方法
这种方法是否行不通,因为引用“默认关闭”为rfcs description says?
【问题讨论】:
标签: vue.js vue-component vuejs3 ref vue-composition-api