【问题标题】:How to emit event from child to parent in Vue3 with <script setup> syntax?如何使用 <script setup> 语法在 Vue3 中从子级向父级发出事件?
【发布时间】:2021-09-16 11:53:58
【问题描述】:

我有以下组件:

<SomeModal is-modal-active="isAddingThing" @close="isAddingThing = false" />

该组件内部如下所示:

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

const props = defineProps({
    isModalActive: Boolean,
})

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

<template>
<V-Modal @close="handleClose">
    ...
</V-Modal>
</template>

如何向父级发射?

【问题讨论】:

    标签: vuejs3


    【解决方案1】:
    • 您根本不需要定义 emit 即可从模板运行 $emit
    • useContext 提供了在 setup 函数中使用的 emit 函数
    • 使用defineEmits 将发射列表添加到组件(相当于emits: 组件的定义)但对发射没有帮助

    useContext

    <template>
      <button @click="action('?')</button>
      <!-- emit is defined through useContext -->
      <button @click="emit('action1','?')">1</button>
      <!-- $emit here doesn't need to be defined -->
      <button @click="$emit('action2','?')">2</button>
    </template>
    <script setup>
      import { defineProps, useContext } from 'vue'
      const { emit } = useContext()
      const action = (id) => emit('action', id);
    </script>
    

    请注意,vetur 扩展可能会告诉您它已被弃用,您应该改用useSlots 和useAttrs。如果您想在脚本中使用emit,显然这些都无济于事。

    getCurrentInstance

    import { defineProps, getCurrentInstance} from 'vue'
    const {emit} = getCurrentInstance()
    

    除了运行发射之外,vue3 还允许(推荐?‍♂️)定义发射,因此组件父级可能知道组件可能发出什么事件。为此,请使用&lt;script setup&gt; 表单,您可以使用defineEmit

    <script setup>
      import { defineEmit } from 'vue'
      const emit = defineEmit(['action'])
      const action = (id) => emit('action', id);
    </script>
    

    这将允许发送 action 发射事件,但如果你发射 doit 尽管它仍然会发射,你会在控制台中收到警告

    [Vue 警告]:组件发出事件“doit”,但它既没有在 emits 选项中声明,也没有作为“onDoit”道具。

    【讨论】:

    • 谢谢!我什至也使用导入 defineEmit learnvue.co/2021/05/… 解决了它
    • 我更喜欢useContext,虽然它看起来不那么僵硬
    • ?使用 learnvue 中的 defineEmit 示例更新答案
    • 用更多的上下文做了另一个更新并添加了例子
    • useContext 和 defineEmit 现在已弃用。使用getCurrentInstance 和defineEmits
    【解决方案2】:

    在 Vue 版本 3.2 中,如果您想从 &lt;script setup&gt; 内部发出一个事件,那么您所要做的就是使用 defineEmits() 内部自动可用的 defineEmits() 方法定义您的发射(您不需要必须导入它),然后您可以通过调用emit('myEventName', myParams) 来发出事件。这是一些示例代码...

    <script setup>
    const emit = defineEmits(['eventA', 'eventB'])
    function btnClick(params) {
        emit('eventA')
        emit('eventB', params)
    }
    </script>
    

    【讨论】:

      猜你喜欢
      • 2017-10-18
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      • 2018-10-06
      • 2019-02-22
      • 2021-04-16
      • 2021-04-15
      • 2021-05-28
      相关资源
      最近更新 更多