Last active
May 2, 2020 21:06
-
-
Save padcom/94104ac7ac2aa0791671dbf873a2c30c to your computer and use it in GitHub Desktop.
DynamicTable - Vue.js example of using dynamic scoped slots
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