You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vue Test Utils中给插槽传入带必填Props的SFC?

解决插槽组件必填Props传递问题

在测试中给插槽传入带必填Props的SFC,有两种实用方法:

方法一:使用Vue渲染函数(h函数)

通过h函数可以明确指定组件及其所需Props,这是最稳妥的通用方式:

import { h } from 'vue';
import List from '../List.vue';
import ListItem from '../components/ListItem.vue';

const factoryMount = () => mount(List, {
  slots: {
    default: () => h(ListItem, { label: '测试项标签' })
  },
});

h函数的第二个参数就是组件的Props对象,直接传入必填的label即可消除警告。

方法二:使用模板字符串(需注册组件)

如果更习惯模板写法,可以直接在插槽中写模板字符串,但要记得全局注册插槽组件:

import List from '../List.vue';
import ListItem from '../components/ListItem.vue';

const factoryMount = () => mount(List, {
  slots: {
    default: `<ListItem label="测试项标签" />`
  },
  global: {
    components: { ListItem }
  }
});

原写法报错原因

直接将组件传入插槽时,Vue Test Utils只会实例化组件但不会传递任何Props,自然触发必填Props的警告。上述两种方法都能在组件实例化时直接传入所需Props,从根源解决问题。

内容的提问来源于stack exchange,提问作者gemmalouise

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 14:59:51