关于vue框架中的createElement方法的第二个参数

想请教一下,vue 框架中createElement方法的第二个参数具体作用是啥,看了官网的文档后对这一参数的用法感到还是比较困惑。

clipboard.png

当我自己敲了个组件试了下后,发现当把第二个参数设置为这样后,会对渲染出来的组件跟节点增加style,class等属性?

import Vue from 'vue'

export default Vue.component('testCreateElement', {
    render: function (createElement) {
        return createElement({
            template: `
                <div @click="clickHandler">
                    <h1>This component is created by render function :):):)</h1>
                    <p>
                        {{statusNum}}
                    </p>
                    <h2>My name is: {{name}}</h2>
                    <h2>My age is: {{age}}</h2>
                    <slot></slot>
                </div>
            `,
            props: ['testProp1', 'testProp2'],
            data: function () {
                return {
                    statusNum: Math.random() * 10000
                }
            },
            methods: {
                clickHandler: function () {
                    this.$data.statusNum = Math.random() * 1000
                }
            }
        }, {
            // 和`v-bind:class`一样的 API
            'class': {
                foo: true,
                bar: false
            },
            // 和`v-bind:style`一样的 API
            style: {
                color: 'red',
                fontSize: '14px'
            },
            // 正常的 HTML 特性
            attrs: {
                id: 'foo'
            },
            // 组件 props
            props: {
                myProp: 'bar'
            }
        }, [
            '先写一些文字',
            createElement('h1', '一则头条')
        ])
    }
})
{
    // 和`v-bind:class`一样的 API
    'class': {
        foo: true,
        bar: false
    },
    // 和`v-bind:style`一样的 API
    style: {
        color: 'red',
        fontSize: '14px'
    }
    ...
}

clipboard.png

阅读 16.6k
2 个回答

第二个参数是属性的设置。比如:class, style, attrs等

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题