v3学习记录
1. 组件上的ref
<script setup>
import {ref,onMounted} from 'vue';
import Child from './Child.vue'
const child = ref(null)
onMounted(()=>{
//child.value 是组件Child的实例
})
</script>
<template>
<Child ref="child">
</template>
使用了<script setup>的组件是默认私有的,父组件无法访问到适用了setup子组件中的任何东西,除非子组件在其中适用defineExpose宏显示暴露出来
<script setup>
import {ref} from 'vue'
const a = 1;
const b = ref(2)
defineExpose({
a,
b
})
</script>
当父组件通过模板引用获得该组件的实例内容时,实例内容为{a:1,b:2}(ref)会自动捷报,和一般的实例一样.
2. 传递props
defineExpose是仅在setup中可用的编译宏命令,不需要显式引入,申明的props会自动暴露给模板,defineExpose会返回一个对象
const props = defineExpose(['title'])
console.log(props.title)
3.defineEmits
defineExpose仅可用于setup中,不需要显式引入,它返回一个等同于$emit方法的emit函数.可以用于在组件的setup中抛出事件,无法直接访问$emit
<script setup>
const emit = defineEmits(['enlarge-text'])
emit('enlarge-text')
</script>

基础点
浙公网安备 33010602011771号