微信小程序自定义组件
开发者可以将页面内的功能模块抽象成自定义组件,以便在不同的页面中重复使用;也可以将复杂的页面拆分成多个低耦合的模块,有助于代码维护。
创建自定义组件:在页面中创建文件夹components,里面放需要的组件文件夹,如下:
下面我们先从写页面开始一步步往下深入
页面
先做出如上的效果,并添加点击切换橘色背景的效果(因为我们要使点击的当前view的class为active,所以需要设置一个变量,当变量等于当前下标时,class=active,下标通过加data-i获得,变量为activeIndex)
<view class="list" style="padding:50rpx 0">
<view class="listLeft">度数</view>
//当手点击时,触发choose函数,choose为获得当前数组的下标,赋值给activeIndex,再通过判断activeIndex===index来使当前class=active
<view bindtap="choose" data-i='{{index}}' class="{{activeIndex===index?'active':''}}" wx:for='{{3}}'>0度</view>
</view>
.list{
display: flex;
margin: 10rpx 0;
}
.list .listLeft{
min-width: 100rpx;
}
.list view{
margin: 0 10rpx;
}
.active{
background: orangered;
color: #fff;
}
// pages/detail/detail.js
//引入外部封装函数
import {
$get,
$attr
} from '../../utils/fun.js'
Page({
//当触发此事件时,activeIndex当前view中data-i的值
choose(e){
let i = $attr(e,'i')
this.setData({
activeIndex:i
})
},
data: {
activeIndex:0
},
})
自定义组件
将上面的代码样式语言放在components中相应文件夹的wxss文件中,我的是放在guige/index.wxcss中
/* pages/components/guige/index.wxss */
.list{
display: flex;
margin: 10rpx 0;
}
.list .listLeft{
min-width: 100rpx;
}
.list view{
margin: 0 10rpx;
}
.active{
background: orangered;
color: #fff;
}
相应的wxml放在对应的wxml中,其中标签之间的变量如{{label}}是其他页面传进的值,通过properties传入,如下是components中的页面,变量为{{}}中的值,来自properties
<!--pages/components/guige/index.wxml-->
<view class="list">
<view class="listLeft">{{label}}</view>
<view bindtap="choose" data-i='{{index}}' class="{{activeIndex===index?'active':''}}" wx:for='{{list}}'>{{item}}</view>
</view>
components的js文件和普通的不一样,方法需放在methods中,data放不需要传递的值,properties放传过来的值,其中的变量作为属性,他的属性值为数组,其他页面传进数据是通过组件上面的属性传递的
properties: {
//传递label,为字符串,value中放默认值
label:{
type:String,
value:'种类'
},
list:{
type: Array
}
},
如下是其他页面引用自定义的组件,在json中定义组件名字,及路径,在页面中用名字引入,传递label和list
<h1 label='种类' list='{{typeList}}'></h1>
{
"usingComponents": {
"h1":"../../components/guige/index"
}
}
组件中也可以定义bind-tab,这样就不用每个view中都新建一个事件了
// pages/components/guige/index.js
import {
$get,
$attr
} from '../../utils/fun.js'
Component({
/**
* 组件的属性列表
*/
properties: {
label:{
type:String,
value:'种类'
},
list:{
type: Array
}
},
/**
* 组件的初始数据
*/
data: {
activeIndex:0
},
/**
* 组件的方法列表
*/
methods: {
//事件方法需保存下methods中
choose(e) {
let i = $attr(e, 'i')
this.setData({
activeIndex: i
})
}
}
})
当然,我们也可以通过提供一个 <slot> 节点,用于承载组件引用时提供的子节点
<view>
<slot></slot>
</view>
当页面引用时,只需写成
<h1 label='label'>111</h1>
但是此方法只适用于传递文本,不能传递数组等类型
组件中数值的变化一般都是通过对data里面的数值进行改变,再通过this.triggerEvent('aa',this.data.count),引用的页面通过组件上bindaa="change",这里的aa可以随便命名,只要保证triggerEvent和bind后面的字符一致就可,通过change方法(change也是可以随意命名)里面的e的参数得到要调用的值
this.triggerEvent('change', this.data.mycount)
<counter bindchange="handleCountChange" count="{{count}}"></counter>
完~