我有以下带有插槽的组件:

<template>
    <div>
        <h2>{{ someProp }}</h2>
        <slot></slot>
    </div>
</template>

由于某些原因,我必须手动实例化这个组件.我就是这样做的:

const Constr = Vue.extend(MyComponent);
const instance = new Constr({
    propsData: { someProp: 'My Heading' }
}).$mount(body);

The problem is: I am not able to create slot contents programmatically.到目前为止,我可以创建简单的基于字符串的插槽:

const Constr = Vue.extend(MyComponent);
const instance = new Constr({
    propsData: { someProp: 'My Heading' }
});

// Creating simple slot
instance.$slots.default = ['Hello'];

instance.$mount(body);

The question is - how can I create 100 programmatically and pass it to the instance I am creating using 101?

Note: I am not using a full build of Vue.js (runtime only). So I don't have a Vue.js compiler available to compile the template on the fly.

推荐答案

我查看了Vue.js个TypeScript定义文件,在Vue组件实例$createElement()上发现了一个未记录的函数.我的猜测是,它是传递给组件的render(createElement)函数的同一个函数.因此,我可以通过以下方式来解决:

const Constr = Vue.extend(MyComponent);
const instance = new Constr({
    propsData: { someProp: 'My Heading' }
});

// Creating simple slot
const node = instance.$createElement('div', ['Hello']);
instance.$slots.default = [node];

instance.$mount(body);

但这显然是没有文件记录的,因此值得怀疑.如果有更好的方法可用,我不会标记它的答案.

Vue.js相关问答推荐

获取深度嵌套对象时无法读取空/未定义的属性

Nuxt3 Build . put文件夹保持空,没有从.nuxt复制任何内容

在哪里可以找到在线沙箱 Vuetify 3 模板来创建最小的可重现示例?

Vue 3 范围滑块中的多个值

vuejs3 youtube-plugin YT 未定义控制台错误

通过元素加中的正则表达式输入电话号码格式

在 Ajax 函数中访问 Vue.js 组件属性

Vue:根元素内容和内容分发槽

使用 jquery-chosen 插件更新 vuejs 模型值

Vue.js 中 Chrome 和 Datalist 的性能问题

如何像 React 中的 {...props} 一样在 Vue 中解构 props?

Vuejs:我应该在 vue-router SPA 中的哪里放置一些常用的 js 工具?

动态注册本地 Vue.js 组件

我可以避免使用 Vue.js 组件的重复样式吗?

Vue 组件中的组件渲染函数中可能存在无限更新循环警告

Vue在按钮单击时添加一个组件

Vue 2.0 设置路由 - 不要使用new来产生副作用

升级到 vue-cli 3 后,HTML 中的空格消失了

将 Vue props与默认值合并

超过最大调用堆栈大小 Vuetify