1、父组件
<template>
<h2>APP父级组件</h2>
<h3>msg:{{msg}}</h3>
<!-- <button @click="msg += '==='">更新数据</button> -->
<button @click="sendmsg">更新数据</button>
<hr/>
<child :msg="msg" @chenemit="chenemit"/>
</template>
<script lang="ts">
import { defineComponent, ref} from 'vue'
//引入子级组件child
import Child from './components/Child.vue'
export default defineComponent({
name: 'App',
//注册组件
components:{
Child
},
setup(){
//定义一个Ref类型的数据
const msg = ref('hello how are you')
function sendmsg(){
msg.value += '==='
}
function chenemit(txt:string){
msg.value += txt
}
return{
msg,
sendmsg,
chenemit
}
}
})
</script>
<style>
</style>
2、子组件
<template>
<h2>Child子级组件</h2>
<h3>msg:{{msg}}</h3>
<button @click="emitxxx">分发事件</button>
</template>
<script lang="ts">
import { defineComponent} from 'vue'
export default defineComponent({
name: 'Child',
props:['msg'],
setup(props,context){
console.log(props.msg)
console.log('setup执行了')
//按钮的点击事件的回调函数
function emitxxx(){
context.emit('chenemit','pp') //朝着定义的'chenemit'发送消息
}
return{
emitxxx
//setup中一般都是返回一个对象,对象中的属性和方法都可以在html模板中直接使用
}
}
})
</script>
<style>
</style>
3、结果