vue3.0 父子组件相互传参
父组件
<template>
<div class="home">
<button @click="onAbout">父组件按钮</button>
<div>{{subVal}}</div>
<div class="subCompt">
<HelloWorld :msg="msg" @onSubNum="onSubNum"/>
</div>
</div>
</template>
<script>
import HelloWorld from '@/components/HelloWorld.vue'
import { reactive, toRefs } from 'vue'
export default {
components: {
HelloWorld
},
setup(){
const state = reactive({
msg:1,
subVal:""
})
const onAbout = ()=>{
return state.msg += 1
}
const onSubNum = (v) =>{
state.subVal = v
}
return {...toRefs(state),onAbout,onSubNum}
}
}
</script>
<style scoped>
.subCompt{
background: rgb(160, 172, 190);
margin: 20px;
}
</style>
子组件
<template>
<div class="hello">
<div>我是子组件值:{{msg}}</div>
<button @click="subPop">我是子组件的按钮</button>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
msg: Number,
},
setup(props, ctx) {
const subPop = () => {
ctx.emit("onSubNum",555);
};
return {
subPop
};
},
};
</script>