Vue 进阶之从 0 到 1 搭建组件库(二)
Vue 进阶之从 0 到 1 搭建组件库(二)
2 button 组件
2.1 初始化
components
目录下创建一个button.vue
组件
<template>
<div class="hm-button">按钮组件</div>
</template>
<script>
export default {
name: 'HmButton'
}
</script>
<style>
</style>
- 在
main.js
文件中全局注册组件
import Vue from 'vue'
import App from './App.vue'
// 引入按钮组件
import HmButton from './components/button'
Vue.config.productionTip = false
// 全局注册
Vue.component(HmButton.name, HmButton)
new Vue({
render: h => h(App)
}).$mount('#app')
- 在
App.vue
中使用注册好的组件
<template>
<div id="app">
<hm-button></hm-button>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style lang="scss">
</style>
2.2 前置知识
- 组件通讯
- 组件插槽
props
校验
2.3 参数支持
参数名 | 参数描述 | 参数类型 | 默认值 |
---|---|---|---|
type |
按钮类型 ( primary / success / warning/ danger/ info ) |
string |
default |
plain |
是否是朴素按钮 | boolean |
false |
round |
是否是圆角按钮 | boolean |
false |
circle |
是否是圆形按钮 | boolean |
false |
disabled |
是否禁用按钮 | boolean |
false |
icon |
图标类名 | string |
无 |
2.4 事件支持
事件名 | 事件描述 |
---|---|
click |
点击事件 |
2.5 基本结构
-
效果
-
使用插槽自定义按钮上面的文字
<template>
<div id="app">
<hm-button>按钮</hm-button>
<hm-button>登陆</hm-button>
<hm-button>删除</hm-button>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style lang="scss">
</style>
- 按钮的基本结构+样式如下
<template>
<button class="hm-button">
<span><slot></slot></span>
</button>
</template>
<script>
export default {
name: 'HmButton'
}
</script>
<style lang="scss" scoped>
.hm-button {
display: inline-block;
line-height: 1;
white-space: nowrap;
cursor: pointer;
background: #fff;
border: 1px solid #dcdfe6;
color: #606266;
-webkit-appearance: none;
text-align: center;
box-sizing: border-box;
outline: none;
margin: 0;
transition: 0.1s;
font-weight: 500;
// 禁止元素的文字被选中
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
padding: 12px 20px;
font-size: 14px;
border-radius: 4px;
&:hover,
&:focus {
color: #409eff;
border-color: #c6e2ff;
background-color: #ecf5ff;
}
}
</style>
2.6 type
属性
- 效果
button
的使用: 目标是可以根据不同的type
的值生成不同样式的按钮
<template>
<div id="app">
<div class="row">
<hm-button>按钮</hm-button>
<hm-button type="primary">按钮</hm-button>
<hm-button type="success">按钮</hm-button>
<hm-button type="info">按钮</hm-button>
<hm-button type="warning">按钮</hm-button>
<hm-button type="danger">按钮</hm-button>
</div>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style lang="scss">
.row {
margin-bottom: 20px;
.hm-button {
margin-right: 20px;
}
}
</style>
button
组件内部实现
<template>
<button class="hm-button" :class="[`hm-button-${type}`]">
<span><slot></slot></span>
</button>
</template>
<script>
export default {
name: 'HmButton',
// 需要对传过来的 props 进行校验
props: {
type: {
type: String, // 数据类型-字符串
default: 'default'
}
}
}
</script>
<style lang="scss" scoped>
@import 'index.scss';
</style>
- 因为样式比较多,所以单独抽离了一个样式文件