Vue.js中的渲染功能

时间:2018-12-07 08:07:15

标签: javascript vue.js vuejs2

我正在尝试通过渲染功能在VueJS中构建一个小的组件,以下是我的<table>组件:

<template>
    <div>
        <table class="table">
                <thead>
                <tr>
                    <th v-for="item in headers">
                        {{ item.title }}
                    </th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="(item, index) in contents">
                    <!--<th scope="row">-->
                        <!--{{ index+1 }}-->
                    <!--</th>-->
                    <td v-for="{ key } in headers">
                        {{ item[key] }}
                    </td>
                </tr>

                </tbody>
        </table>
    </div>
</template>

我为此做了以下渲染功能:

render (createElement) {
    return createElement('table', {class: 'table'}, [
        createElement('thead', {}, [
            createElement('tr',
                this.headers.map(a => createElement('th', a.title)))
        ], createElement('tbody',
            this.contents.map(b => createElement('tr',
                this.headers.map(c => createElement('td', c[key]))))))
    ])
}

我遇到

错误
  

渲染错误:“ ReferenceError:未定义键”

仅供参考,我的数据集看起来像这样:

data() {
    return {
        headers: [
            { title: '#', key: 'index' },
            { title: 'First Name', key: 'first_name'},
            { title: 'Last Name', key: 'last_name'},
            { title: 'Username', key: 'username' }
        ],
        contents: [
            { index: 1, first_name: 'John', last_name: 'Stone', username: '@john' },
            { index: 2, first_name: 'Lisa', last_name: 'Nilson', username: '@lisa' },
            { index: 3, first_name: 'Larry', last_name: 'the Bird', username: '@twitter' }
        ]
    }
}

我想知道如何从map数据集中的headers中取出密钥

2 个答案:

答案 0 :(得分:2)

括号错误

    return createElement('table', { class: 'table' }, [
      createElement('thead', {}, [
        createElement('tr',
          this.headers.map(a => createElement('th', a.title)))
      ]), <--here
      createElement('tbody', 
        this.contents.map(b => createElement('tr',
            this.headers.map(c => createElement('td', b[c['key']]))
          )
        )
      )
    ])

答案 1 :(得分:1)

您对createElement调用的构造方式有疑问(第一个数组不正确)。如果您正确地布局代码,就可以看到它。

  • 我将createElement重命名为h以便于阅读(h是惯例)。
  • c[key]应该是b[c.key]
  • 不建议使用abc作为变量名,请使用描述性名称。
  • 此处使用staticClass代替class是次要的优化。

未经测试:

render(h) {
  return h('table', { staticClass: 'table' }, [
    h('thead', [
      h('tr', this.headers.map(header =>
        h('th', header.title)
      ))
    ]),
    h('tbody', this.contents.map(item =>
      h('tr', this.headers.map(header =>
        h('td', item[header.key])
      ))
    ))
  )
}