vue.js - 无法在 vue 3 组合 api 中的组件上使用模板引用

标签 vue.js vue-component vuejs3 ref vue-composition-api

我想从父级获取 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/

相关文章:

javascript - Foundation 6 模式在 vue.js 组件中不起作用

events - Vue this.$emit ('eventName' ) 组件 A 中的事件没有触发组件 B 中的 this.$on ('eventName' , callbackFunc) ,我是否放错了处理程序?

javascript - Vue props update - 组件渲染函数中可能有无限更新循环

javascript - vue3 + vee-validate - handleSubmit 不返回值

typescript - 为什么函数在 vue 3 设置 block 中立即执行

Vue.js 从方法访问变量

ios - NativeScript 找不到模块组件/主页

javascript - VueJS : Reset/Clear value from input

javascript - Vue.js - 单向数据绑定(bind)从子级更新父级

vue.js - 如何以编程方式销毁 Vue3 组件实例?