封装 button 组件
前置知识:
- 组件通讯
- 组件插槽
- props 校验
参数支持:
参数名 | 参数描述 | 参数类型 | 默认值 |
---|---|---|---|
type | 按钮类型(primary/success/warning/danger/info) | string | default |
plain | 是否是朴素按钮 | boolean | false |
round | 是否是圆角按钮 | boolean | false |
circle | 是否是圆形按钮 | boolean | false |
disabled | 是否禁用按钮 | boolean | false |
icon | 图标类名 | string | 无 |
事件支持:
事件名 | 事件描述 |
---|---|
click | 点击事件 |
使用插槽:
直白的说,凡是组件中内容可以动态设置的地方,都需要用到slot插槽来自定义内容。
使用 slot 来定义按钮上的文本内容:
<template>
<button class="wyh-button">
<span>
<slot></slot>
</span>
</button>
</template>
在使用时就可以直接输入相关内容,即可定义按钮文本内容:
<template>
<div>
<wyh-button>登录</wyh-button>
</div>
</template>
设置自己喜欢的 button 样式,这里 css 样式就不做过多介绍。
type 参数的实现
让按钮支持 type 属性,使得按钮呈现不同的样式:
- 父组件传递 type 属性
<template>
<div id="app">
<one-button type="primary">primary 按钮</one-button>
</div>
</template>
- 子组件接收 type,限制 type 的值必须为 String 类型并设置默认值
export default {
name: 'oneButton',
props: {
type:{
// 此时对 props 进行校验,值接收 String 类型的 type 值
type: String,
// 设置默认值:如果不传值,那么使用 default
default: 'default'
}
}
}
- 动态绑定类名控制样式,定好样式前缀,通过传过来的 type 动态绑定类名,用不同的样式。
<template>
<button class="wyh-button" :class="[`wyh-button-${type}`]">
<span><slot></slot></span>
</button>
</template>
- 设置不同的样式,例如:
.wyh-button-primary {
color: #fff;
background-color