Created
May 8, 2020 11:44
-
-
Save padcom/ce5dce9b9190a4cf3036c068dac53bbb to your computer and use it in GitHub Desktop.
Coding with Padcom - DynamicTable component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Dynamic table</title> | |
| <script src="https://unpkg.com/vue"></script> | |
| <style> | |
| td.name { | |
| font-weight: bold; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <div id="app"> | |
| <dynamic-table :columns="columns" :rows="users"> | |
| <template #address="{ row: user }"> | |
| {{ user.address.city }}, {{ user.address.street }} | |
| </template> | |
| <span>No users loaded</span> | |
| </dynamic-table> | |
| </div> | |
| <template id="dynamic-table"> | |
| <div> | |
| <table class="data-table" v-if="rows.length > 0"> | |
| <thead> | |
| <tr> | |
| <th v-for="column in columns" :key="column.field" :class="column.classes"> | |
| {{ column.title }} | |
| </th> | |
| </tr> | |
| </thead> | |
| <tbody> | |
| <tr v-for="row in rows" :key="row.id"> | |
| <td v-for="column in columns" :key="column.field" :class="column.classes"> | |
| <slot :name="column.field" :row="row"> | |
| {{ row[column.field] }} | |
| </slot> | |
| </td> | |
| </tr> | |
| </tbody> | |
| </table> | |
| <slot v-else>No data</slot> | |
| </div> | |
| </template> | |
| <script> | |
| Vue.component('dynamic-table', { | |
| template: '#dynamic-table', | |
| props: { | |
| columns: { type: Array, default: () => [] }, | |
| rows: { type: Array, default: () => [] } | |
| }, | |
| }) | |
| async function fetchUsers() { | |
| const response = await fetch('https://jsonplaceholder.typicode.com/users') | |
| return response.json() | |
| } | |
| new Vue({ | |
| el: '#app', | |
| data: { | |
| message: 'Hello, world!', | |
| columns: [ | |
| { field: 'name', title: 'Name', classes: 'name' }, | |
| { field: 'email', title: 'email' }, | |
| { field: 'address', title: 'Address' } | |
| ], | |
| users: [] | |
| }, | |
| async mounted() { | |
| this.users = await fetchUsers() | |
| } | |
| }) | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment