ref
作用:用于注册模板引用。
- 用在普通DOM标签上,获取的是DOM节点。
- 用在组件标签上,获取的是组件实例对象。
defineExpose()
默认情况下在<script setup>语法糖下组件内部的属性和方法是不开放给父组件的
可以通过defineExpose编译宏指定哪些属性和方法允许访问
子组件 child.vue
<script setup>
const count = ref(99)
const sayHi = () => {
console.log('hi', count.value)
}
defineExpose({
count,
sayHi
})
</script>
如此处理之后,父组件才能调用
<script setup>
import { ref } from 'vue'
const childeRef = ref()
onMounted(() => {
childeRef.value.sayHi() // 调用子组件函数
})
</script>
<template>
调用一下子组件
{{childeRef.count}}
<child ref="childeRef" />
<template>