在vue3的组合式API中,父传子的基础套路完全一样,基础思想依旧为:父传子是通过prop进行传入,子传父通过调用自定义事件完成
实现步骤
-
setup函数提供俩个参数,第一个参数为props,第二个参数为一个对象context
-
props为一个对象,内部包含了父组件传递过来的所有prop数据,context对象包含了attrs,slots, emit属性,其中的
emit
可以触发自定义事件的执行从而完成子传父
父组件代码如下:
<template>
<son :msg="msg" @get-msg="getMsg"></son>
</template>
<script>
import { ref } from 'vue'
import Son from './components/son'
export default {
components: {
Son
},
setup() {
const msg = ref('this is msg')
function getMsg(msg) {
console.log(msg)
}
return {
msg,
getMsg
}
}
}
</script>
子组件代码如下:
<template>
<div>
{{msg}}
<button @click="setMsgFromSon">set</button>
</div>
</template>
<script>
export default {
props: {
msg: {
type: String
}
},
emits: ['get-msg'], // 声明当前组件触发的自定义事件
setup(props,context) {
function setMsgFromSon(){
context.emit('get-msg','这是一条来自子组件的新的msg信息')
}
return {
setMsgToSon
}
}
}
</script>