快捷键 vb3s
父组件:
<template>
<div>
<child ref="childRef" :title="title" @onTitle="setTitle" />
<button @click="getChild">获取child实例</button>
</div>
</template>
<!-- 此写法,它支持顶层async ,在此代码块中你可以直接写await -->
<script setup>
import {
ref } from 'vue'
// 导入的组件,导入进来后,直接可以在模板中使用,无须再用 components 注册
import child from './components/child.vue'
let title = ref('我是一个父组件')
let childRef = ref()
const setTitle = tit => (title.value = tit)
const getChild = () => {
// vue3中的setup很安全,仅仅可以获得实例,获取不到数据
console.log(childRef.value)
}
</script>
<style lang="scss" scoped>
</style>
子组件:
<template>
<div>
<h3>child组件 -- {
{ title }}</h3>
<button @click="setTitle">修改父组件标题</button>
</div>
</template>
<script setup>
import {
ref } from 'vue'
// 接受props中的属性
defineProps({
title: {
type: String }
})
// 定义自定义事件
const emit = defineEmits(['onTitle'])
const setTitle = () => {
// 事件名、数据
emit('onTitle', Date.now() + '')
}
const name = ref('aaaa')
const fn = () => {
}
// 子组件可以选择向外暴露的数据
defineExpose({
name,
fn
})
</script>
<style lang="scss" scoped></style>