実務にて複数のデザインのボタンを扱うことがほとんどだと思います。
そこで今日は便利に使いまわせるボタンコンポーネントを作ってみたいと思います。
// input.vue
<template>
// 親コンポーネントからもらったpropsを受け取る
<component :is="tag" :class="classes" v-bind="$attrs">
// 親コンポーネントの文言取得
<slot>{{ label }}</slot>
</component>
</template>
<script>
export default {
name: "InputButton",
// propsを定義
props: {
// 文言
label: {
type: String,
default: "",
},
// ボタンの種類
type: {
type: String,
default: "primary",
validator: (value) => {
return ["primary", "common"].includes(value) !== -1;
},
},
// ボタンの大きさ
size: {
type: String,
default: "m",
// "large", "medium", "small"の三種類から選んでね
validator: (value) => {
return ["l", "m", "s"].includes(value) !== -1;
},
},
},
computed: {
tag() {
return "button";
},
classes() {
// クラスをセットする
const classes = ["button", `${this.type}`, `--${this.size}`];
return classes;
},
},
};
</script>
<style lang="scss" scoped>
// 受け取った値に応じる為にcssを書いていく
.button {
display: block;
text-align: center;
font-weight: 800;
text-decoration: none;
position: relative;
cursor: pointer;
border: none;
width: 100%;
margin: 0 auto 30px;
&.--l {
width: 300px;
height: 46px;
line-height: 46px;
font-size: 1.7rem;
border-radius: 23px;
font-weight: 600;
}
&.--m {
width: 200px;
height: 32px;
line-height: 32px;
font-size: 1.3rem;
border-radius: 16px;
}
&.--s {
width: 120px;
height: 32px;
line-height: 32px;
font-size: 1.3rem;
border-radius: 16px;
}
&.red {
background: red;
color: #000;
}
&.blue {
background: blue;
color: #fff;
}
}
</style>
// HelloWorld.vue
<template>
<div class="hello">
<template>
// 全通りのボタンを属性に指定
<input-button :size="'l'" :type="'blue'"> hoge </input-button>
<input-button :size="'m'" :type="'blue'"> hoge </input-button>
<input-button :size="'s'" :type="'blue'"> hoge </input-button>
<input-button :size="'l'" :type="'red'"> fuga </input-button>
<input-button :size="'m'" :type="'red'"> fuga </input-button>
<input-button :size="'s'" :type="'red'"> fuga </input-button>
<input-button :size="'l'"> def </input-button>
<input-button :size="'m'"> def </input-button>
<input-button :size="'s'"> def </input-button>
</template>
</div>
</template>
<script>
// ボタンコンポーネントをインポート
import InputButton from "./input";
export default {
name: "HelloWorld",
components: {
InputButton,
},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>