親コンポーネントからv-imgへsrc属性を渡すための書き方
..
Vuetifyに限らず、propsや属性等をいろいろ書く場合、一度ラップした上でそのラッパーの方を使い回すのが効率的だと考えられます。
それをv-img
でもやろうとしたときの記録です。
##コンポーネント構造
components
└── Common
└── Img.vue // v-imgをラップしている
└── Example
└── Parts
└── Img.vue // Common/Img.vueをラップしている
└── Icon.vue // Example/Parts/Img.vueをラップしている
##方法
/Common/Img.vue
<template>
<v-img
aspect-ratio="1"
v-bind="$attrs"
>
<template v-slot:placeholder>
<v-row
class="fill-height ma-0"
align="center"
justify="center"
>
<v-progress-circular
indeterminate
color="grey lighten-5"
></v-progress-circular>
</v-row>
</template>
</v-img>
</template>
/Example/Parts/Img.vue
<template>
<CommonImg :src="$attrs" />
</template>
/Example/Icon.vue
<template>
<ExamplePartsImg :src="image_src" />
</template>
<script>
export default {
data() {
return {
image_src: require("@/assets/img/tagicons/nuxt.js.svg"),
}
}
}
</script>
大元でv-bind="$attrs"
とし、ラッパーではv-bind:src="$attrs"
として値を受ける。ラッパーのラッパーではrequire
で読み込んだパスをv-bind:src="$attrs"
として渡す。
##これを複数の属性で行う
src
に加えてlazy-src
も渡したい。そういうときは、ラッパーとラッパーのラッパーをこのように編集。
/Example/Parts/Img.vue
<template>
<CommonImg v-bind="$attrs" />
</template>
/Example/Icon.vue
<template>
<ExamplePartsImg v-bind="attributes" />
</template>
<script>
export default {
data() {
return {
attributes: {
src: require("@/assets/img/tagicons/nuxt.js.svg"),
lazySrc: require("@/assets/img/tagicons/nuxt.js.svg")
}
}
}
}
</script>
学んだことまとめ
-
$attrs
というプロパティは、オブジェクト形式で書いた属性をバインドさせられる。 -
v-img
に画像のパスを渡す場合、値としてrequire
で読み込んだパスを記述することで実現できる。