传递数据 defineProps
vue3中使用defineProps
来接收父组件传递过来的数据
不需要引入 defineProps
// 父组件
<headMessage
:game-type="gameType"
:group-name="yellowName"
:score="yellowScore"
:time="yellowTime"
:pause-game="pauseGame"
></headMessage>
//子组件接收数据
const props = defineProps<{
gameType: string,
groupName: string,
score: number,
time: Array<number>,
pauseGame: boolean,
}>();
//可以把数据结构出来
const { gameType,groupName,score, time ,pauseGame} = reactive(props)
//或者是直接调用
console.log("队伍信息头部页面",props.gameType,props.groupName,props.score, props.time,props.pauseGame)
传递事件 defineEmits
不需要引入 defineEmits
子组件可以通过调用内置的[emit](https://staging-cn.vuejs.org/api/component-instance.html#emit)
方法,通过传入事件名称来抛出一个事件:
//子组件
<template>
<div class="blog-post">
<h4>{{ title }}</h4>
<button @click="next">Enlarge text</button>
</div>
</template>
<script setup>
//定义事件名,多个事件可以写到一个数组里
const emit = defineEmits(["next-word","first-end","second-word"])
//触发事件,
const next = ()=>{
//向上抛出
emit('next-word')
//也可以传递参数
emit("first-end",'哈哈哈哈哈哈')
}
</script>
//父组件
<template>
<headMessage
@next-word="changeWord"
@first-end="firstWordEndEvent"
></headMessage>
</template>
<script setup>
//定义事件名,多个事件可以写到一个数组里
const emit = defineEmits(["next-word","first-end","second-word"])
//触发事件
const changeWord = ()=>{
console.log("下一个单词")
}
const firstWordEndEvent = (value)=>{
console.log("能接收到参数======",value)
}
</script>