簡體   English   中英

在Vuejs中渲染函數

[英]Render function in Vuejs

我正在嘗試通過渲染函數在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' }
        ]
    }
}

我想知道我們如何能夠從取出鑰匙mapheaders

錯誤的括號

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM