设计图
需求多种场景下的按钮,且每种场景下有三种不同状态,按钮预留size和disable选项。
template部分
- 直接写一个button,然后预留一个slot,用于在button中插入文字。
- 绑定class,此时class的绑定有几种形式,详情见vue.js官方文档Class 与 Style 绑定
:class="{active: isActive, “text-danger”: hasError}" // 变量是boolean
:class="[isActive, hasError]". // 变量是字符串
:class="[isActive ? activeClass : ‘’, errorClass]" // 三目运算
:class="[{active: isActive}, errorClass]" - 绑定事件,点击按钮,抛出一个click事件,让父组件接收到
<template>
<button :class="['btn', type, size]" :disabled="disabled" @click="handleClick()">
<slot></slot>
</button>
</template>
script部分
给size和disabled设置默认值并进行类型检测。 type是给用户的接口,主要是用来改变class从而控制样式。
<script>
export default {
name: 'myButton',
props: {
type: {
type: String,
default: 'confirm-shallow',
},
size: {
type: String,
default: 'small',
},
disabled: {
type: Boolean,
default: false,
},
},
methods: {
handleClick(data) {
this.$emit('click', data);
},
},
};
</script>
<style lang="less" scoped>
/*按钮通用状态*/
button {
outline: none;
border: 0;
cursor: pointer;
}
.btn {
font-style: normal;
font-weight: 500;
font-size: 18px;
}
/*按钮的disabled状态*/
button[disabled] {
opacity: 0.6;
cursor: not-allowed;
}
/*控制按钮的size,两种状态。*/
.small {
width: 144px;
height: 40px;
.button-text {
line-height: 40px;
}
}
.large {
width: 272px;
height: 60px;
.button-text {
line-height: 60px;
}
}
/*confirm-shallow 第一种场景下三种状态*/
.confirm-shallow {
background: rgba(76, 132, 255, 0.1);
border: 2px solid #4c84ff;
box-sizing: border-box;
border-radius: 4px;
color: #4c84ff;
}
.confirm-shallow:hover {
background: #709dff;
color: #d8dce9;
}
.confirm-shallow:active {
background: #4170d9;
color: #d8dce9;
}
/*confirm-medium 第二种场景下三种状态*/
.confirm-medium {
background: #4c84ff;
border-radius: 4px;
color: #d8dce9;
}
.confirm-medium:hover {
background: #709dff;
}
.confirm-medium:active {
background: #4170d9;
}
/*confirm-deep 第三种场景下三种状态*/
.confirm-deep {
background: #4c84ff;
border-radius: 4px;
color: #181e35;
}
.confirm-deep:hover {
background: #709dff;
}
.confirm-deep:active {
background: #4170d9;
}
</style>
全局注册组件
import Button from '../src/components/button';
Vue.component('v-button', Button);