1. 父子组件调用
父页面有一个 msg 为父组件传给子组件的参数,@sendMsg 为接收子组件返回的参数的方法
父页面
<template>
<div class="home">
<TheWelcome msg="Home" @sendMsg="handle"></TheWelcome>
</div>
</template>
<script>
import TheWelcome from "../components/TheWelcome.vue"
export default {
name : "Home",
components:{
TheWelcome
},
setup(){
const handle = value => {
console.log("setup -> value",value)
};
return {
handle
}
}
}
</script>
2、 子组件 TheWelcome
点击按钮的时候,触发事件, emit 为提交事件
<template>
<div class="hello">
{{msg}}
<input type="text" v-model="state.num1" >
+
<input type="text" v-model="state.num2" >
=
{{state.result}}
<button type="button" @click="clickEvent()">event</button>
</div>
</template>
<script>
import {reactive,computed} from "vue"
export default {
name : "HelloWorld",
props :{
msg :String
},
setup(props,{emit}){
console.log("props=",props)
const state = reactive({
num1:0,
num2:0,
result: computed(()=>parseInt(state.num1) + parseInt(state.num2))
});
const clickEvent = () => {
console.log("click")
emit('sendMsg',state.result)
}
return {
state,clickEvent
};
}
}
</script>