Vue2で孫コンポーネントにprops, events, slotsをリレーする
by wintyo
HTML
<div id="vue-app"></div>
<template id="vue-app-root-template" type="text/x-template">
<v-app>
<div class="mb-1">選択件数: {{ $data.selectedItems.length }}</div>
<data-table-with-search
:value="$data.selectedItems"
:headers="$data.headers"
:items="$data.items"
show-select
@input="$data.selectedItems = $event"
>
<template v-slot:[`item.sex`]="{ item }">
<v-chip
:color="item.sex === '男性' ? 'blue' : 'red'"
label
dark
>{{ item.sex }}</v-chip>
</template>
<template v-slot:[`item.url`]="{ item }">
<a
:href="item.url"
target="_blank"
rel="noreferrer noopener"
>{{ item.url }}</a>
</template>
<!-- コンポーネントで拡張したslotも順番次第で上書きできる -->
<!-- <template v-slot:top>top!</template> -->
</data-table-with-search>
</v-app>
</template>
<template id="data-table-with-search-template" type="text/x-template">
<v-data-table
v-bind="$attrs"
:search="$data.searchWord"
v-on="$listeners"
>
<template v-slot:top>
<v-text-field
v-model="searchWord"
label="Search"
outlined
dense
hide-details
/>
</template>
<!-- v-slot:topを上書きされたくない場合は、このループを最初に書く -->
<template v-for="(_, slot) in $scopedSlots" v-slot:[slot]="props">
<slot :name="slot" v-bind="props" />
</template>
</v-data-table>
</template>
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/faker@5.5.3/dist/faker.min.js"></script>
SCSS
@import 'https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css';
body {
padding: 8px;
}
JavaScript
console.log(Vue.version);
Vue.use(Vuetify);
function createDummyData() {
return _.times(100).map((i) => ({
id: i,
name: faker.name.lastName() + ' ' + faker.name.firstName(),
sex: faker.random.arrayElement(['男性', '女性']),
email: faker.internet.email(),
tel: faker.phone.phoneNumberFormat(),
url: faker.internet.url(),
}));
}
const DataTableWithSearch = Vue.extend({
template: '#data-table-with-search-template',
inheritAttrs: false,
data() {
return {
searchWord: ''
}
},
mounted() {
console.log('$attrs:', this.$attrs);
console.log('$listeners:', this.$listeners);
console.log('$scopedSlots:', this.$scopedSlots);
}
});
new Vue({
el: '#vue-app',
template: '#vue-app-root-template',
vuetify: new Vuetify(),
components: { DataTableWithSearch },
data() {
return {
headers: [
{ text: 'id', value: 'id' },
{ text: 'name', value: 'name' },
{ text: 'sex', value: 'sex' },
{ text: 'url', value: 'url' },
{ text: 'email', value: 'email' },
],
items: createDummyData(),
selectedItems: [],
}
}
});