为什么要封装组件?
可以增加代码的复用性、灵活性,从而提高开发效率。例如:多个页面都使用到了搜索框,但是每个页面的搜索框样式又有不同,那此时我们就可以把搜索框封装成一个组件,利用props去接收样式,修改样式。
封装的搜索框组件:
<template>
<view class="search-content">
<view class="search-box"
:style="{
'background-color': bgcolor,
'justify-content':wordsLocation}"
>
<u-icon name="search" size="22" color="#999"></u-icon>
<text class="placeholder" >{{holderwords}}</text>
</view>
</view>
</template>
<script>
export default{
props:{
bgcolor:{
type:String,
default:'#fff'
},
holderwords:{
type:String,
default:'搜索商品'
},
wordsLocation:{
type:String,
default:'flex-start'
}
}
}
</script>
<style lang="scss" scoped>
.search-content{
padding:10rpx 20rpx;
height:100rpx;
display:flex;
align-items: center;
.search-box{
height:70rpx;
width:100%;
padding-left:20rpx;
// background-color: #fff;
display: flex;
align-items: center;
// justify-content: flex-start;
border-radius: 30rpx;
}
.placeholder{
color:#999;
font-size:26rpx;
}
}
</style>
引用组件步骤:
1.导入封装的组件
2.利用components注册组件
3.页面中使用组件
组件1引用:
<template>
<view>
<!-- 这里不是原生标签不能直接用click,可以加@click.native,或者组件发射自定义事件 -->
<my-search holderwords="搜索你想要的商品" @click.native="goToSearch"></my-search>
</view>
</template>
<script>
import mySearch from '@/components/my-search.vue'
export default{
components:{
mySearch
},
</script>
组件2引用:
<template>
<view>
<my-search bgcolor="#f7f7f7" wordsLocation="center" @click.native="goToSearch"></my-search>
<view class="scroll-content">
</view>
</template>
<script>
import mySearch from '@/components/my-search.vue'
export default{
components:{
mySearch
},
</script>
显示效果: