自定义组件
1、在根目录中创建components目录
2、在components目录中声明组件 右击新建component。一个文件夹为一个组件
js文件Component({options: {styleIsolation: 'apply-shared',//控制组件样式隔离 isolated apply-shared sharedpureDataPattern: /^_/ //指定data中那些数据是纯数据字段 可用正则表达式},/*** 组件的属性列表*/properties: {//组件对外开放的属性声明在此处//简化的声明方式 只指明了类型max: Number,//完整的声明方式指明了类型和默认值min:{type: Number,value: 10,}},/*** 组件的初始数据*/data: {count: 0},/*** 组件的方法列表*/methods: {//组件中的方法需要声明在methods中addCount(){if(this.data.count<this.properties.max){this.setData({count: this.data.count+1}),this._showCount()}},_showCount(){wx.showToast({title: 'count是:'+this.data.count,icon: 'none'})},addN1(){if(this.data.count<this.properties.max){this.setData({n1: this.data.n1+1})}},addN2(){if(this.data.count<this.properties.max){this.setData({n2: this.data.n2+1})}}}/*** 数据监听器*/observers:{'n1, n2': function(newN1, newN2){//监听多个数据时用,隔开this.setData({sum: newN1+newN2})}}lifetimes:{//组件周期函数created:{//*** 组件实例刚被创建时执行},attached:{//*** 组件实例进入页面树节点时执行},ready: {//组件渲染完成后执行},moved: {//组件实例被移动时执行},detached: {//组件实例被删除时执行},error: {//组件方法抛出错误时执行}},pageLifetimes:{//组件监听当前所在页面生命周期show: function() {}, //组件所在页面被展示时执行hide: function() {}, //组件所在页面被隐藏时执行resize: function() {} //组件所在页面尺寸变化是执行}})组件的wxml文件<text>我是组件</text><view>{{count}}</view><button bindtap="addCount">点击</button><view>{{n1}}+{{n2}}={{sum}}</view><button bindtap="addN1">点击</button><button bindtap="addN2">点击</button><text>---我是组件---</text>
3、全局引用
json文件 pages平级"usingComponents": {"my-test1": "/components/test/test"//左侧为组件名称 右侧为组件路径}
应用在对应页面的wxml文件中<my-test1 max="20" min="15"></my-test1>
4、页面局部引入自定义组件
引入对应的json文件中"usingComponents": {"my-test1": "/components/test/test"//左侧为组件名称 右侧为组件路径}
应用在对应页面的wxml文件中<my-test1 max="20" min="15"></my-test1>