vue.js 从模板参考中获取 prop

txu3uszq  于 2023-03-24  发布在  Vue.js
关注(0)|答案(1)|浏览(121)

有没有可能通过模板引用获取vue组件的属性?我可以使用defineExpose,但我对是否有其他解决方案感兴趣。我使用vue 3 composition API。

<script setup lang="ts">
const childRef = ref()

const foo = () => {
  console.log(childRef.value.someData)
}
</script>

<template>
  <Child ref="childRef" some-data="my special data" />
</template>

<style scoped lang="scss"></style>
z6psavjg

z6psavjg1#

您可以尝试使用ref属性将childRef模板ref绑定到子组件。例如-

const childRef = ref<typeof Child>()

我们还需要使用defineComponents函数导入Child组件,这样我们就可以在components选项中访问它。

defineComponent({
  components: {
    Child,
  },
  setup() {
    return {
      childRef,
      foo
    }
  },
})

最后,您可以像这样访问子组件的属性-

const foo = () => {
  console.log(childRef.value?.someData)
}

这里是demo。

相关问题