工作原理
在子组件中调用emit方法触发父组件的方法实现传值
父组件 p.vue
bash
<template>
<div>
<ChildComponent @childValue="handleChildValue"></ChildComponent>
<button @click="getChildValue">获取子组件的值</button>
{{receivedChildValue}}
</div>
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './child.vue';
const receivedChildValue = ref('');
const handleChildValue = (value) => {
receivedChildValue.value = value;
};
const getChildValue = () => {
console.log('Child Value:', receivedChildValue.value);
};
</script>
子组件:child.vue
bash
<template>
<div>
<p>子组件的值: {{ childValue }}</p>
</div>
</template>
<script setup>
import { ref, getCurrentInstance } from 'vue';
const childValue = ref('czs');
const instance = getCurrentInstance();
//子组件发生值给父组件,通过childValue事件触发
instance.emit('childValue', childValue.value);
</script>