如何在 Vuejs 渲染函数中复制插槽? [英] How can I duplicate slots within a Vuejs render function?

查看:43
本文介绍了如何在 Vuejs 渲染函数中复制插槽?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过插槽传递内容的组件.我正在使用渲染函数来输出内容.我使用渲染函数的原因是我想多次复制内容.当我使用此代码时,一切正常:

I have a component which is passed content via a slot. I'm using a render function to output the content. The reason I'm using a render function is because I want to duplicate the content multiple times. When I use this code, everything works fine:

render(createElement){
    return createElement('div', {}, this.$slots.default);
}

当我传递的数据发生变化时,输出也会发生变化.

When I data that is being passed changes, the output changes as well.

但是,由于我想复制插槽内容,我现在正在尝试:

However, since I want to duplicate the slot content, I'm now trying this:

return createElement(
    'div', {},
        [
            createElement('div', { }, this.$slots.default),
            createElement('div', { }, this.$slots.default)
        ]
    )

现在的问题是,当slot内容从组件外部改变时,只有第二个div中的内容得到更新,第一个div中的内容保持不变..

Now the problem is, when the slot content changes from outside the component, only the content in the second div gets updated, the content in the first div stays the same..

我在这里遗漏了什么吗?

Am I missing something here?

推荐答案

我无法解释为什么会发生这种情况.但该文档确实提到VNodes 必须是唯一的".在渲染函数中.参见 https://vuejs.org/v2/guide/render-function.html#约束.

I can't explain why it happens. But the doc does mention that "VNodes Must Be Unique" in a render function. See https://vuejs.org/v2/guide/render-function.html#Constraints.

无论如何,这是一个 VNode 克隆功能,它有效,这是我从 https://jingsam.github.io/2017/03/08/vnode-deep-clone.html.

Anyway, this is a VNode cloning function, which works, which I discovered from https://jingsam.github.io/2017/03/08/vnode-deep-clone.html.

function deepClone(vnodes, createElement) {
    function cloneVNode(vnode) {
        const clonedChildren = vnode.children && vnode
            .children
            .map(vnode => cloneVNode(vnode));
        const cloned = createElement(vnode.tag, vnode.data, clonedChildren);
        cloned.text = vnode.text;
        cloned.isComment = vnode.isComment;
        cloned.componentOptions = vnode.componentOptions;
        cloned.elm = vnode.elm;
        cloned.context = vnode.context;
        cloned.ns = vnode.ns;
        cloned.isStatic = vnode.isStatic;
        cloned.key = vnode.key;
        return cloned;
    }
    const clonedVNodes = vnodes.map(vnode => cloneVNode(vnode))
    return clonedVNodes;
}

使用方法:

render(createElement) {
    return createElement('div', {}, [
        createElement('div', {}, this.$slots.default),
        createElement('div', {}, [...deepClone(this.$slots.default, createElement)])
    ])
}

演示:https://jsfiddle.net/jacobgoh101/bz3e0o5m/

这篇关于如何在 Vuejs 渲染函数中复制插槽?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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