vue3 setup中子組件拋出事件通過(guò)context.emit
案例
- index.vue 父頁(yè)面
<template>
<div>
<child1 :name="name" title="標(biāo)題一" @itemclick="itemclickFun"/>
</div>
</template>
<script>
import { ref } from 'vue'
// 導(dǎo)入子組件
import child1 from '../../components/child1'
export default {
name: 'index4',
components: {
child1
},
setup(){
const name = ref('傳入子組件的name');
// 監(jiān)聽(tīng)子組件拋出的事件
const itemclickFun = (e)=>{
console.log('子組件給的值:', e);
}
return { name, itemclickFun }
}
}
</script>
- child1.vue 子組件
<template>
<div @click="clickInfo">
子組件 == {{name1}}, {{title1}}
</div>
</template>
<script>
import { reactive } from 'vue'
export default {
name: 'child1',
props: {
name: String,
title: String
},
setup(props, context){
const name1 = reactive(props.name)
const title1 = reactive(props.title)
// 子組件點(diǎn)擊事件
const clickInfo = ()=>{
// 拋出事件
context.emit('itemclick', {name: 'emitClick'})
}
return { name1, title1, clickInfo };
}
}
</script>