emit:
父子组件的耦合纽带,子组件不能修改父组件的数据
如需要修改,通过某个信号去通知父组件更新,再传递到子组件
具体解释:父组件注册了一个函数,但是它不会自己去执行这个函数,它需要收到一个信号才会自己去执行。什么叫注册了一个函数呢?说白了,就是它在自己本身组件内部定义了一个函数,但是这个函数在没有收到 “信号的时候是不会去执行的”。
如果你能明白上一段的意思,那么你基本上就知道 “信号” 究竟是谁发出来的了。让我们回到子组件内部,在子组件内,我们需要去拿到父组件注册的那个函数名字。也就是showWin,来准备通知父组件。
子组件 child.vue
点击按钮,触发函数onCloseds,函数发出信号通知父组件更新 emit("showWin",true)
<template>
<button @click="onCloseds">请更新数据</button>
<template>
<script setup>
import {defineEmits} from 'vue'
const emit = defineEmits(['showWin'])
const onCloseds = () => {
emit("showWin",true)
}
</script>
父组件parent.vue
父组件接受到信号showWin,执行函数upWin去更新数据
<template>
<Child @showWin="upWin"></Child>
</template>
<script setup>
import Child from './Child.vue'
const upWin = ((isflag) => {
console.log('子组件通知我更新啦!)
})
</script>