我正在尝试通过渲染函数在 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]
。- 不鼓励使用
a
、b
和c
作为变量名,使用描述性名称。 - 在这里使用
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/