Vue Composition API:定义发射

Vue Composition API: Defining emits

defining custom events Vue 鼓励我们通过 emits 选项在组件上定义发出的事件时:

app.component('custom-form', {
  emits: ['inFocus', 'submit']
})

使用 Vue 3 的组合 API,当独立组合函数发出自定义事件时,是否可以在组合函数中定义这些事件?

不,因为组合函数在 setup 钩子内部使用,它无法访问其他选项,如 methodsemits:

export default defineComponent({
    name: "layout",
    emits: ['showsidebar'],
    setup(props, { emit }) {
        const showSidebar = ref(true);
        const { breakpoints } = useBreakpoint();
        watch(breakpoints, (val) => {
            showSidebar.value = !(val.is === "xs" || val.is === "sm");
            emit('showsidebar',showSidebar.value);
        });
        return {
            showSidebar,
        };
    },
    data() {
        // ...
    },
});

在示例中,useBreakpoint 仅提供组件可以使用的一些逻辑。如果有一种方法可以在组合函数中定义 emits 选项,那么该函数将始终发出事件,即使该函数仅在定义所发出事件的处理程序的组件内部使用。

使用新的脚本设置语法,您可以按如下方式进行:

<script setup>
 import { defineEmits,watch,ref } from 'vue'
    
    const emit = defineEmits(['showsidebar'])
    const showSidebar = ref(true);
    const { breakpoints } = useBreakpoint();
    watch(breakpoints, (val) => {
            showSidebar.value = !(val.is === "xs" || val.is === "sm");
            emit('showsidebar',showSidebar.value);
        });
</script>

我是这样用脚本设置语法做的:

<script setup>
    import { defineEmits } from 'vue'

    const emit = defineEmits(['close'])

    const handleClose = () => {
        emit('close')
    }
</script>

如果你想获得全部context:

    setup(props, context) {
       // console.log(context)
       context.emit("update:modelValue", data)
    },

如果您使用 script setup,您可以使用 defineEmits,这是一个编译器宏,您不必导入它:

<script setup>
const emit = defineEmits(['inFocus', 'submit'])

emit('inFocus')
</script>

您还可以使用对象语法,它允许执行事件验证:

<script setup>
const emit = defineEmits({
  // No validation
  inFocus: null,

  // Validate submit event
  submit: ({ email, password }) => {
    if (email && password) return true
    else return false
  }
})

function submitForm(email, password) {
  emit('submit', { email, password })
}
</script>

注意:无论验证如何,都会发出 submit 事件,但如果验证未通过,您将收到 Vue 警告:

[Vue warn]: Invalid event arguments: event validation failed for event "submit".

See it live


使用 TS 打字:

<script setup lang="ts">
const emit = defineEmits<{
  (e: 'change', id: number): void
  (e: 'update', value: string): void
}>()
</script>