返回

Vue 3 可重用文件 emit 详细指南:解决 'Property 'emit' does not exist' 错误

vue.js

Vue 3 可重用/可组合文件中使用 emit 的深入指南

问题:emit 错误“Property 'emit' does not exist on type 'ComponentInternalInstance | null'"

在 Vue 3 中,可重用或可组合文件中的 emit 可能会引发 "Property 'emit' does not exist on type 'ComponentInternalInstance | null'" 错误。

解决方案:使用 getCurrentInstance()

为了解决此问题,我们需要使用 getCurrentInstance() 函数来获取组件实例,然后才能访问 emit:

  1. 导入 getCurrentInstance()

    import { getCurrentInstance } from 'vue'
    
  2. 获取组件实例:

    在可重用/可组合文件的函数中,使用 getCurrentInstance() 获取组件实例:

    const { emit } = getCurrentInstance()
    
  3. 使用 emit:

    现在你可以使用 emit 来触发自定义事件:

    emit('id', '123')
    

完整示例

假设我们有一个名为 useGoo.ts 的可重用文件,其中包含一个函数 myId() 来触发 id 事件。修改后的文件如下:

import Swal from "sweetalert2/dist/sweetalert2.js";
import { getCurrentInstance } from 'vue'

export default function useModal() {

  const { emit } = getCurrentInstance()

  function myId() {
    emit('id', '123')
  }

}

通过这些步骤,你将能够在 Vue 3 的可重用/可组合文件中有效地使用 emit。

提示

  • 确保在使用 emit 之前已正确安装 Vue 3。
  • 使用 emit 时,请确保使用正确的事件名称。
  • 如果 emit 仍然不起作用,请检查控制台中的错误消息以获取更多详细信息。

常见问题解答

1. 为什么在可重用/可组合文件中不能直接使用 this.emit?

因为在这些文件中,this 上下文指向文件本身,而不是组件实例。因此,我们需要使用 getCurrentInstance() 来获取组件实例。

2. 什么时候应该使用可重用/可组合文件中的 emit?

可重用/可组合文件中的 emit 用于在这些文件和使用它们的组件之间进行通信。例如,它可以用来触发父组件中的事件,或者与其他组件进行交互。

3. emit 是否仅适用于可重用/可组合文件?

不,emit 也可用于普通的 Vue 组件中。然而,在可重用/可组合文件中使用 emit 时需要使用 getCurrentInstance()

4. 是否可以在可重用/可组合文件中监听 emit 事件?

是的,你可以使用 onMounted() 生命周期钩子来监听可重用/可组合文件中触发的 emit 事件。

5. emit 是否适用于跨组件通信?

是的,emit 可用于在不同的组件之间传递事件,即使它们不在同一层次结构中。