javascript - Vuejs 中的渲染函数

标签 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]))))))
    ])
}

我得到一个错误

Error in render: "ReferenceError: key is not defined"

仅供引用,我的数据集如下所示:

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 中取出 key 的 headers数据集

最佳答案

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])
      ))
    ))
  )
}

关于javascript - Vuejs 中的渲染函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53665530/

相关文章:

javascript - 在同一选项卡与新选项卡中开始下载的原因?

javascript - 获取函数内的变量并将其分配给其范围之外的另一个变量

javascript - VueJS 组件

javascript - Vue.js - 单向数据绑定(bind)从子级更新父级

javascript - 渐变按钮到背景颜色在悬停时闪烁

javascript - 如何从 JS 中的事件对象构建 CSS 选择器?

javascript - 如何通过单击选项卡本身以外的其他内容来切换 VueJS Vuetify 中的选项卡

vue.js - Vue js如何向表格中的单元格添加组件

javascript - div 元素不使用 javascript 更新

javascript - 将 &lt;input v-for> 传递给 php