父传子
父组件:
<template>
<ChildComponent :msg="parentMessage" />
</template
<script setup>
import ChildComponent from './ChildComponent.vue'
const parrentMessage = 'Hello from Parent';
</script>
子组件(ChildComponent.vue):
<template>
<div>{{msg}}</div>
</template>
<script setup>
const props = defineProps({msg:String})
</script>
子传父
子组件(ChildComponent.vue):
<template>
<button @click = "sendValue">点击向父组件传值</button>
</template>
<script setup>
import {defineEmits} from 'vue'
const emit = defineEmits(['customEvent'])
const sendValue = ()=>{
const value = "这是从子组件传的值"
emit('customEvent',value) //使用 emit 函数来触发 customEvent 事件,将value值作为参数传递。
}
</script>
父组件:
<template>
<div>
<ChildComponent @custom-event="handleChildEvent" />
<p>从子组件接收到的值:{{receivedValue}}</p>
</div>
</template>
<script setup>
import {ref} from 'vue'
import ChildComponent from './ChildComponent.vue'
const receivedValue = ref(null)
const handleChildEvent = (value)=>{
receivedValue.value = value
}
</script>