首先我们知道vue里面包含有父子组件
但是你知道如果要进行一个element的手动组件封装
怎么封装吗
1首先第一步
首先我们建立一个组件
最好设置在一个文件目录下比如components
只是一个普通的组件
叫做OneButton.vue
<template>
<button class="one-button">
按钮组件
</button>
</template>
<script>
export default {
name: 'oneButton'
}
</script>
<style lang="scss">
</style>
要想使用该组件
就需要进行全局注册
就是在main.js里面注册了
import Vue from 'vue'
import App from './App.vue'
// 第一步:导入button组件
import OneButton from './components/button.vue'
Vue.config.productionTip = false
// 第二步:注册组件,设置(组件名,组件)
Vue.component(OneButton.name, OneButton)
new Vue({
render: h => h(App)
}).$mount('#app')
注册完成以后就可以进行使用了
<template>
<div id="app">
<one-button>按钮</one-button>
</div>
</template>
<script>
export default {
name: 'App',
components: {}
}
</script>
<style lang="scss">
</style>
到这里
我们可以看到 就会显示一个普通按钮了
但是吧 这样的封装过于简单
能不能实现更加复杂的操作呢
于是
我们需要封装一个有element-ui风格的组件
好 那我们继续实现
我们先让文字可以自由的输入
那就要利用插槽了
<template>
<button class="one-button">
<span><slot></slot></span>
</button>
</template>
我们的文件需要做以上处理
<template>
<div>
<one-button>歌谣</one-button>
<one-button>帅气</one-button>
<one-button>关注我</one-button>
</div>
</template>
加上基本样式
<style lang="scss">
.one-button{
display: inline-block;
line-height: 1;
white-space: nowrap;
cursor: pointer;
background: #ffffff;
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;
-moz-user-select: none;
-ms-user-select: none;
padding: 12px 20px;
font-size: 14px;
border-radius: 4px;
&:hover,
&:hover{
color: #409eff;
border-color: #c6e2ff;
background-color: #ecf5ff;
}
}
</style>
这样文字的效果就实现了
到了这里 你又想element里面可以控制type属性控制按钮样式
怎么可以实现呢
父元素传递type值
<template>
<div id="app">
<div class="row">
<one-button>按钮</one-button>
<one-button type="primary">primary按钮