如何同过 store 传过来的数据 通过render 函数自动渲染
发布于 7 年前 作者 zeroy 2492 次浏览 来自 问答
粉丝福利 : 关注VUE中文社区公众号,回复视频领取粉丝福利

最近写了很多组件,但是我觉得组件用起来有点过于麻烦了,所以想同过store传数据直接render元素,但是都失败了 //home store

export default {
    state: {
        elements: function (h) {
            return [
                h('Nav', {width: '100%', height: '40px', backgroundColor: 'green', position: 'top'},
                    [
                        h('Menu',{
                            tag: "ul",
                            grid: "column",
                            device: "phone tables desktop tv",
                            width: "0 12 12 12",
                            direction: "row",
                        })
                    ])
            ]

        },
    }

//home.js

    export default {
        render(create){
            return create('div', {
                attrs: {
                    id: 'app'
                }
            },this.$store.state.home.elements(create))
        }
    }

失败原因: render function or template not defined in component: anonymous

那样我就换种方式 //home store

export default {
    state: {
        elements: [
            {
                name: 'Nav',
                props: {width: '100%', height: '40px', backgroundColor: 'green', position: 'top'},
                parent: undefined,
                children: [
                    {
                        name: 'Menu',
                        props: {
                            tag: "ul",
                            grid: "column",
                            device: "phone tables desktop tv",
                            width: "0 12 12 12",
                            direction: "row",
                        },
                        children: undefined,
                        parent: 'Nav'
                    }
                ]
            },
        ]
    }
}

//home.js

    export default {
        computed: {
            home(){
                return this.$store.state.home.elements
            }
        },
        render(create){
            return create('div', {
                attrs: {
                    id: 'app'
                }
            }, innerDom.call(this, create))
        }
    }

    function innerDom(create) {
        let element = this.home
        function loop() {
             element.forEach(el=>{
                if(el.children){
                    element = el
                }
// 数组逻辑但差不多用尽了
            })
        }
        loop()
    }

fail reason :不能正确的插入dom 和 不能正确的渲染

有没有人成功的

回到顶部