Vue3 之context.emit

1,609 阅读1分钟

context.emit(fn, $event)作用是子组件将自定义事件向父组件传递。

例子:

父组件:

<template>
  <Switch v-model:value="bool" />
</template>
<script>
import { ref } from 'vue'
import Switch from '../lib/Switch.vue'
export default {
    components: {Switch},
    setup(){
        const bool = ref(false)
        return {bool}
    }
}
</script>

*注:v-model:value="bool"等价于:value="bool" @update:value="bool = $event"

子组件:

<script lang="ts">
import { ref } from 'vue'
export default {
    props: {
        value: Boolean  
    },
    setup(props,context){
        const toggle = ()=> {
            context.emit("update:value", !props.value)
        }
        return {toggle}
    }
}
</script>