CSSを割り当てる【Vue.js】
コンポーネントを使いまわしたい
具体的には下のUserIcon.vueを色んなとこで使いたい。でもサイズは各々違う大きさにしたい 今回はpropsで親から指定することにしました
UserIcon.vue
<template> <div class="user-icon" :style="styles"> <img src="../../assets/images/user.png" class="user-icon-image"> </div> </template> <script> export default { props: ['width'], computed: { styles() { return { '--width': this.width } } } } </script> <style scoped> .user-icon { // デフォルトのwidth --width: 130px; width: var(--width); } </style>
UserPost.vue
<UserIcon :width="width" /> ... ... export default { data() { return { width: '100px' }; }, }
カスタムプロパティを定義して、style属性で後からwidthを上書きしています。UserPost.vueではサイズをちょっと小さくしたいので100pxを指定
ちゃんと大きさが違ってますね