Vue3 子【emit 】传父【监听】

<!-- 父组件 -->
<template>
    <h1>I am ParentComponent</h1>
    <ChildComponent @child-click="zCf"/>
    <h2>{{ x }}</h2>
</template>

<script setup>
import ChildComponent from './ChildComponent.vue'
import { ref } from 'vue';
const x = ref('')
const zCf = (value) => {
    x.value = value;
    console.log(x.value)
}
</script>
<!-- 子组件 -->
<template>
    <h2>I am ChildComponent</h2>
    <h3>使用emit实现子传父</h3>
    <button @click="ziChuanFu">点击我,子传父</button>
</template>

<script setup>
import { defineEmits } from 'vue';
const emit = defineEmits(['child-click'])
const ziChuanFu = () => {
    emit('child-click',1)
}
</script>

总结:子组件通过emit()获取父组件中绑定的方法名@child-click 并传递值,父组件就能获取到参数。

posted @ 2024-07-04 15:13  林财钦  阅读(1)  评论(0编辑  收藏  举报