使用Provide和Inject简单实例

今天碰到一个控制台错误提示:

Extraneous non-emits event listeners (showTodoListModal) were passed to component but could not be automatically inherited because component renders fragment or text root nodes. If the listener is intended to be a component custom event listener only, declare it using the "emits" option.

原来是因为我在<component>组件上写了emits方法导致的;
经过优化,把emits改成provide / inject就解决了,记录一下:

原来代码

父组件

const showTodoModal = () => { }
<keep-alive :include="keepAliveList">
  <component :is="newComponent(Component, route)" @showTodoModal="showTodoModal" />
</keep-alive>

孙子组件

const emits = defineEmits(['showTodoModal'])
const showTodoModal = () => {
  emits('showTodoModal')
}

改造后的代码

父组件

import { provide } from 'vue'
provide('showTodoModal', () => { }
<keep-alive :include="keepAliveList">
  <component :is="newComponent(Component, route)" />
</keep-alive>

孙子组件

import { inject } from 'vue'
const showTodoModal = inject('showTodoModal')
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容