如何以编程方式创建 Vue.js 插槽? [英] How to create Vue.js slot programmatically?
问题描述
我有以下带插槽的组件:
<div><h2>{{ someProp }}</h2><插槽></插槽>
模板>
由于某些原因,我必须手动实例化这个组件.这就是我的做法:
const Consr = Vue.extend(MyComponent);const 实例 = new Consr({propsData: { someProp: '我的标题' }}).$mount(body);
问题是:我无法以编程方式创建插槽内容.到目前为止,我可以创建简单的基于字符串的插槽:
const Consr = Vue.extend(MyComponent);const 实例 = new Consr({propsData: { someProp: '我的标题' }});//创建简单的槽instance.$slots.default = ['Hello'];实例.$mount(body);
问题是 - 如何以编程方式创建 $slots
并将其传递给我使用 new
创建的实例?
注意:我没有使用完整版本的 Vue.js(仅限运行时).所以我没有可用于即时编译模板的 Vue.js 编译器.
我查看了 Vue.js
的 TypeScript 定义文件,我在 Vue 组件实例上发现了一个未公开的函数:$createElement()
.我的猜测是,它与传递给组件的 render(createElement)
函数的函数相同.因此,我可以将其解决为:
const Consr = Vue.extend(MyComponent);const 实例 = new Consr({propsData: { someProp: '我的标题' }});//创建简单的槽const node = instance.$createElement('div', ['Hello']);instance.$slots.default = [节点];实例.$mount(body);
但这显然是无证的,因此是有问题的方法.如果有更好的方法可用,我不会将其标记为已回答.
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);
The question is - how can I create $slots
programmatically and pass it to the instance I am creating using new
?
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.
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屋!