父子通信
父传子
1.父组件给子组件添加属性传值
const myCount = ref(10)
...
<son :count="myCount"/>
2.子组件通过defineProps编译器宏接收
const props = defineProps({
count: Number
})
3.子组件使用
{{count}}
子传父
1. 父组件实现处理函数
const getMsg = (msg) =>{
console.log(msg)
}
2. 父组件添加消息监听
<son @get-message="getMsg">
3. 子组件通过defineEmits编译器宏生成emit方法发送
const emit = defineEmits(['get-message'])
const senMsg = () =>{
emit('get-message','这是要传递的参数')
}
跨层通信
传递数据
1.顶层组件中写:
provide('key', 'value')
2.底层组件中写:
const topData = inject('key')
传递方法
1.顶层组件中写:
const setCount = () =>{
count.value++
}
provide('setCountKey', setCount)
2.底层组件中写:
const setCount= inject('setCountKey')