小程序允许我们使用自定义组件的方式来构建页面。
自定义组件
是不是用的微信的组件感觉很爽啊,如果不够用怎么办?
类似于页面,一个自定义组件由 json
wxml
wxss
js
4个文件组成
首先需要在 json
文件中进行自定义组件声明
同时,还要在 wxml
文件中编写组件模板,在 wxss
文件中加入组件样式
注意:在组件wxss中不应使用ID选择器、属性选择器和标签名选择器。
| |
| <view class="inner"> |
| {{innerText}} |
| <slot></slot> |
| </view> |
在自定义组件的 js
文件中,需要使用 Component()
来注册组件,并提供组件的属性定义、内部数据和自定义方法
| Component({ |
| properties: { |
| |
| innerText: { |
| type: String, |
| value: 'default value', |
| } |
| }, |
| data: { |
| |
| someData: {} |
| }, |
| methods: { |
| |
| customMethod: function(){} |
| } |
| }) |
首先要在页面的 json
文件中进行引用声明。还要提供对应的组件名和组件路径
| { |
| |
| "usingComponents": { |
| |
| "component-tag-name": "path/to/the/custom/component" |
| } |
| } |
| #页面中wxml |
| <my-con title="{{变量名}}"><my-con/> |
| #再组件中 |
| properties: { |
| title:{ |
| type:String, |
| value:"你好" |
| } |
| } |
| 页面 |
| <my-com title="{{title}}" bind:icre="icre"></my-com> |
| 页面中js |
| icre:function(e){ |
| console.log(e) |
| this.setData({ |
| num:this.data.num+1 |
| }) |
| }, |
组件中的wxml
| <button bindtap='clickpush'>加我</button> |
组件中的js
| clickpush:function(e){ |
| console.log(e) |
| this.triggerEvent("icre",{"index":13},{}) |
| } |