美文网首页微信小程序开发微信小程序开发者
微信小程序-快速完成一个自定义组件

微信小程序-快速完成一个自定义组件

作者: foolchen | 来源:发表于2019-02-20 21:03 被阅读5次

与页面(Page)相似,组件也由jsonwxmlwxssjs四个文件组成。

与页面不同的是,需要在组件对应的json文件中作出如下声明:

{
  "component": true
}

以表示当前创建的是一个自定义组件。目前通过微信小程序开发者工具创建组件时,json文件中会自动生成这个定义,无需手动处理。

组件的简单定义

组件中wxmlwxss文件的编写与普通页面没有不同。需要注意的是可以在wxss文件中使用:host选择器来指定组件的默认样式。

代码示例如下:

<!--components/component-user.wxml-->
<view>
  <text>这是自定义组件User</text>
</view>
/* components/component-user.wxss */

/* 此处使用:host选择器来指定组件的默认样式 */
:host {
  color: blue;
  font-style: italic;
}

组件的使用

如果需要在某个页面中引用组件,则需要在这个页面对应的json文件中对需要使用的组件进行声明。此处以index页面为例:
index.json文件中声明要引用的组件:

{
  "usingComponents": {
    "user": "/components/component-user"
  }
}

user是为组件声明的别名,作为在index.wxml中引用组件的标签名。
index.wxml中引用组件:

<!-- index.wxml -->
<view>
  <text>index.wxml</text>
  <user />
</view>
效果如下:

组件模板

插入单个节点

如果要在自定义组件中特定位置插入一个节点,则此时需要使用组件模板。
模板定义如下:

<!--components/component-user.wxml-->
<view>
  <text>这是自定义组件User</text>
  <!-- 使用slot标签作为插入view的节点 -->
  <slot />
</view>

index.wxml中引用如下:

<!-- index.wxml -->
<view class="container">
  <text>index.wxml</text>

  <user>
    <!-- 这个view节点会插入到slot标签处作为自定义组件的一个节点 -->
    <view style="color:#F78AE0">这个view会被插入到自定义组件的slot标签处</view>
  </user>
</view>

效果如下:


注意:可以在同一个slot标签处插入多个节点。

向特定位置插入节点

自定义组件默认仅支持向slot处插入节点。如果想在一个自定义组件的特定位置插入节点的话,首先需要在js文件开启支持多个slot的声明。

// components/component-user.js
Component({
  options: {
    // 支持多个slot
    multipleSlots: true
  }
})

并且在wxml文件中为slot命名:

<!--components/component-user.wxml-->
<view>
  <text>这是自定义组件User</text>
  <!-- 使用slot标签作为插入view的节点 -->
  <slot name="another-slot" />
  <view style='width:100%;height:1px;background:black' />
  <slot name="slot" />
</view>

然后在index.wxml中使用通过指定slot的名字来指定插入的位置:

<!-- index.wxml -->
<view class="container">
  <text>index.wxml</text>

  <user>
    <!-- 这个view节点会插入到slot标签处作为自定义组件的一个节点 -->
    <view style="color:#F78AE0" slot="slot">这个view会被插入到slot处</view>
    <view style="color:#6638F0" slot="another-slot">这个view会被插入到another-slot处</view>
  </user>
</view>

效果如下:


注意:在开启了多slot支持后,如果在组件中存在没有命名的slot,并且index.wxml中也有未指定插入位置的节点,则默认插入无名称的slot处。

事件绑定

在使用模板时,如果要为绑定的节点绑定事件,则添加在模板内和引用处都可以,具体可以根据业务需求来区分。
比如引用自定义组件的多处业务逻辑完全相同,则可以将事件绑定在模板中,减少重复代码。如果引用自定义组件处业务有所不同,则可以在引用处进行事件绑定。
在模板中绑定事件时,wxml文件中代码与普通页面中的代码相同,区别在于js文件中方法的定义:

<!--components/component-user.wxml-->
<view>
  <text>这是自定义组件User</text>
  <!-- 使用slot标签作为插入view的节点 -->
  <slot name="another-slot" />
  <view style='width:100%;height:1px;background:black' />
  <slot name="slot" catchtap="onSlotClick" />
</view>
// components/component-user.js
Component({
  options: {
    // 支持多个slot
    multipleSlots: true
  },
  /**
   * 组件的方法列表
   */
  methods: {
    onSlotClick: function(event) {
      console.log("onSlotClick in component-user.js")
    }
  }
})

在组件模板中绑定事件时,需要将事件的监听方法定义在methods中。

事件的冒泡顺序

在使用事件模板时其实可以在模板wxml文件和页面wxml文件中都对同一个节点进行绑定,此时事件的冒泡顺序可能会让一部分人感到困扰。
index页面中绑定事件代码如下:

<!-- index.wxml -->
<view class="container">
  <text>index.wxml</text>

  <user>
    <!-- 这个view节点会插入到slot标签处作为自定义组件的一个节点 -->
    <view style="color:#F78AE0" slot="slot" bindtap="onSlotClick">这个view会被插入到slot处</view>
    <view style="color:#6638F0" slot="another-slot">这个view会被插入到another-slot处</view>
  </user>
</view>
Page({
  onSlotClick: function(event) {
    console.log("onSlotClick in index.js")
  }
})

此时点击slot,输出如下:


有的同学会认为component-user中的事件先响应而index中的事件后。
其实这是种错误的认知。这些同学错误的将index.wxml中的节点当做了component-user.wxml的外层节点,而实际上index.wxml中定义的节点是要插入到component.user.wxml中的,实际为component-user.wxml中的子节点。

绑定数据

为自定义组件绑定数据和为模板绑定数据差别不大。区别在于为模板绑定数据时需要使用属性data-<data-set-name>,而为自定义组件绑定数据需要预先定义要绑定数据的属性。
首先在component-user.js中定义要绑定事件的属性:

// components/component-user.js
Component({
  options: {
    // 支持多个slot
    multipleSlots: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
    // 用于接收传入的数据
    user: Object
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onSlotClick: function(event) {
      console.log("onSlotClick in component-user.js")
    }
  }
})

component-user.js根据定义的属性绑定数据:

<!--components/component-user.wxml-->
<view>
  <text>这是自定义组件User</text>
  <!-- 使用slot标签作为插入view的节点 -->
  <slot name="another-slot" />
  <view style='width:100%;height:1px;background:black' />
  <slot name="slot" catchtap="onSlotClick" />

  <view>name:{{user.name}}</view>
  <view>age:{{user.age}}</view>
  <view>gender:{{user.gender}}</view>
</view>

然后在引用组件的时候就可以使用user属性来为组件传递数据:

<!-- index.wxml -->
<view class="container">
  <text>index.wxml</text>
  <!-- 使用user属性来向组件传递数据 -->
  <user user="{{user}}">
    <!-- 这个view节点会插入到slot标签处作为自定义组件的一个节点 -->
    <view style="color:#F78AE0" slot="slot" bindtap="onSlotClick">这个view会被插入到slot处</view>
    <view style="color:#6638F0" slot="another-slot">这个view会被插入到another-slot处</view>
  </user>
</view>
Page({
  onReady: function() {
    this.setData({
      user: {
        name: "自定义组件示例",
        age: "0",
        gender: "undetermined"
      }
    })
  },

  onSlotClick: function(event) {
    console.log("onSlotClick in component-user.js")
  }
})
显示效果如下:

behaviors

behaviors用于在不同组件间进行代码共享。类似于Java中多个不同的类实现了相同的接口,则都具备了该接口的特性。示例如下:
定义一个behavior

// component-behavior.js

module.exports = Behavior({
  properties: {
    userInBehavior: Object
  },
  methods: {
    onSlotClick: function(event) {
      console.log("onSlotClick called in component-behavior.js")
    }
  },
  lifetimes: {
    created() {
      console.log("created called in component-behavior.js")
    },
    attached() {
      console.log("attached called in component-behavior.js")
    },
    detached() {
      console.log("detached called in component-behavior.js")
    },
    ready() {
      console.log("ready called in component-behavior.js")
    }
  },
})

我们在component-behavior.js中定义了属性userInBehavioronSlotClick方法,并且添加了生命周期的回调。

component-user.js也添加生命周期回调,并且引入behavior

// components/component-user.js
var mBehavoir = require('component-behavior.js')

Component({
  options: {
    // 支持多个slot
    multipleSlots: true
  },
  // 此处引入定义的behavior
  behaviors: [mBehavoir],
  /**
   * 组件的属性列表
   */
  properties: {
    // 用于接收传入的数据
    user: Object
  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 此处监听方法的定义与behavior中相同,behavior中的同名方法会被覆盖
    onSlotClick: function(event) {
      console.log("onSlotClick in component-user.js")
    }
  },
  lifetimes: {
    created() {
      console.log("created called in component-user.js")
    },
    attached() {
      console.log("attached called in component-user.js")
    },
    detached() {
      console.log("detached called in component-user.js")
    },
    ready() {
      console.log("ready called in component-user.js")
    }
  }
})

component-user.wxml修改如下:

<!--components/component-user.wxml-->
<view>
  <text>这是自定义组件User</text>
  <!-- 使用slot标签作为插入view的节点 -->
  <slot name="another-slot" />
  <view style='width:100%;height:1px;background:black' />
  <slot name="slot" catchtap="onSlotClick" />

  <view>name:{{user.name}}</view>
  <view>age:{{user.age}}</view>
  <view>gender:{{user.gender}}</view>
</view>

至此,behavior的定义和引入完成。运行程序,控制台输出如下:


我们发现component-behavior.jscomponent-user.js中的生命周期回调方法被依次调用。
在执行点击操作,结果如下:
我们发现component-behavior.js中的事件监听方法没有执行。
component-user.js中的事件监听方法注释掉再重试:
这次component-behavior.js中的事件监听方法被调用了。
总结一下:
behavior中定义的生命周期回调与组件模板中定义的生命周期回调不会互相覆盖,而普通方法(例如事件监听方法为组件模板中的方法覆盖behavior中的方法)。

我们还在component-behavior.js中定义了一个新的属性userInBehavior,尝试在index中传递数据:

Page({
  onReady: function() {
    this.setData({
      user: {
        name: "自定义组件示例",
        age: "0",
        gender: "undetermined"
      },
      userInBehavior: {
        name: "name in behavior"
      }
    })
  },

  onSlotClick: function(event) {
    console.log("onSlotClick in index.js")
  }
})

index.wxml中绑定数据:

<!-- index.wxml -->
<view class="container">
  <text>index.wxml</text>
  <!-- 使用user属性来向组件传递数据 -->
  <user user="{{user}}" userInBehavior="{{userInBehavior}}">
    <!-- 这个view节点会插入到slot标签处作为自定义组件的一个节点 -->
    <view style="color:#F78AE0" slot="slot" bindtap="onSlotClick">这个view会被插入到slot处</view>
    <view style="color:#6638F0" slot="another-slot">这个view会被插入到another-slot处</view>
    
    <view style="color:red">这个节点使用了behavior中的数据:name={{userInBehavior.name}}</view>
  </user>
</view>

为了让未指定插入位置的节点能够正常显示,还需要在component-user.wxml中添加一个未命名的slot标签:

<!--components/component-user.wxml-->
<view>
  <text>这是自定义组件User</text>
  <!-- 使用slot标签作为插入view的节点 -->
  <slot name="another-slot" />
  <view style='width:100%;height:1px;background:black' />
  <slot name="slot" catchtap="onSlotClick" />

  <view>name:{{user.name}}</view>
  <view>age:{{user.age}}</view>
  <view>gender:{{user.gender}}</view>

  <slot />
</view>

效果如下:


此处仅介绍了小程序自定义组件的简单使用,如果需要了解更复杂的特性,请访问官方文档-自定义组件

相关文章

网友评论

    本文标题:微信小程序-快速完成一个自定义组件

    本文链接:https://www.haomeiwen.com/subject/cfykyqtx.html