如何以编程方式创建Vue.js插槽? [英] How to create Vue.js slot programmatically?

查看:56
本文介绍了如何以编程方式创建Vue.js插槽?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following component with a slot:

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

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

For some reasons, I have to manually instantiate this component. This is how I am doing it:

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. So far, I can create simple string based slot:

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

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

instance.$mount(body);

问题是-如何以编程方式创建 $ slots 并将其传递给使用 new 创建的实例?

The question is - how can I create $slots programmatically and pass it to the instance I am creating using new?

注意:我没有使用完整版本的Vue.js(仅用于运行时).因此,我没有Vue.js编译器可用于即时编译模板.

推荐答案

我查看了 Vue.js 的TypeScript定义文件,并在Vue组件实例上发现了一个未记录的函数: $ createElement().我的猜测是,它与传递给组件的 render(createElement)函数的函数相同.因此,我能够将其解决为:

I looked into TypeScript definition files of Vue.js and I found an undocumented function on Vue component instance: $createElement(). My guess is, it is the same function that is passed to render(createElement) function of the component. So, I am able to solve it as:

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);

但这显然是无证的,因此是有问题的方法.如果有更好的方法,我不会将其标记为已回答.

But this is clearly undocumented and hence questionable approach. I will not mark it answered if there is some better approach available.

这篇关于如何以编程方式创建Vue.js插槽?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆