微信小程序自定义组件
组件的定义
配置文件- 要编写一个自定义组件,首先需要在
json
文件中进行自定义组件声明(将component
字段设为true
)。 - 使用用已注册的自定义组件前,首先要在页面的
json
文件中进行引用声明。此时需要提供每个自定义组件的标签名
和对应的自定义组件文件路径
(标签名称只能是小写字母、中划线和下划线的组合,组件根目录名不能以“wx-”为前缀)。
1 2 3 4 5 6 7 8 9 10 11 |
//自定义组件component.json { "component" : true } //引用自定义组件的页面 page.json { "usingComponents" : { "component-tag-name" : "../component/component" } } |
wxml文件
在组件模板中可以提供一个 <slot> 节点,用于承载组件引用时提供的子节点。默认情况下,一个组件的wxml中只能有一个slot。需要使用多slot时,可以在组件js中声明启用
options: {multipleSlots: true }
,以不同的 name 来区分。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<!-- 这是自定义组件的内部WXML结构(component.wxml)--> <view class = 'wapper' > <text> this is component</text> <slot name= "slot1" ></slot> 我在中间 <slot name= "slot2" ></slot> </view> <!-- 以下是对一个自定义组件的引用 (page.wxml)--> <view> <text>This is Page</text> <component-tag-name inner-text= "Some text" class = "page-component" > <view slot= "slot1" class = "slot" >来自page页面,通过slot标签</view> <view slot= "slot2" ></view> </component-tag-name> </view> |
- wxss文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
//component.wxss .wapper{ background-color:#ccc; width: 100 %; height:auto; } .slot{ color:red; } //page.wxss .page-component{ color:#fff; //有效,继承样式 padding:10px; //无效 } .slot{ color:green; } |
js文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
//component.js Component({ options: { multipleSlots: true // 在组件定义时的选项中启用多slot支持 }, properties: { // 这里定义了innerText属性,属性值可以在组件使用时指定 innerText: { type: String, value: 'default value' , //不存在此属性时 } }, data: { // 这里是一些组件内部数据 someData: {} }, methods: { // 这里是一个自定义方法 customMethod: function(){} } }) |
通过上面的代码和显示结果可以看出:
- slot样式受
page.wxss
里的.slot
影响显示绿色,不受component.wxss
的.slot
影响显示红色。 - 继承样式,如 font 、 color ,会从组件外继承到组件内。除继承样式外, app.wxss 中的样式、组件所在页面的的样式对自定义组件无效。例子中
.page-component
的color:#fff
能生效,而padding
则不生效。
Page与Component数据交互
Tip:page代指引用组件页面,component代指自定义组件
- page > component
- page在引用组件时能通过属性值设置,component.js在
properties
获取。 - page在引用组件时通data-xxx设置,component.js在
this.dataset
获取。
1 2 |
<!-- page.wxml --> <component-tag-name fromPage= "来自Page" data-other= "from dataset" ></component-tag-name> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
Component({ properties: { formPage: String //简写 /* myProperty: { // 属性名 type: String, // 类型(必填),目前接受的类型包括:String, Number, Boolean, Object, Array, null(表示任意类型) value: '', // 属性初始值(可选),如果未指定则会根据类型选择一个 observer: function(newVal, oldVal){} // 属性被改变时执行的函数(可选),也可以写成在methods段中定义的方法名字符串, 如:'_propertyChange' } */ }, attached:function(){ console.log( this .properties.fromPage); console.log( this .data.fromPage); //用data也能访问properties //设置properties值用setData() this .setData({ fromPage: '改变了' }); console.log( this .properties.fromPage); //通过dataset获取data-other的值 console.log( this .dataset.other); } }) |
参考文档:微信小程序-自定义组件