Функция рендеринга в Вуэйс - PullRequest
0 голосов
/ 07 декабря 2018

Я пытаюсь построить небольшой компонент в 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 голосов
/ 07 декабря 2018

У вас есть проблема с тем, как вы структурировали свои 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])
      ))
    ))
  )
}
0 голосов
/ 07 декабря 2018

неправильные скобки

    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']]))
          )
        )
      )
    ])
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...