Skip to content

组件

定义组件

  • 对于功能组件,建议放在 components 文件夹中;
  • 对于页面组件,建议放在 pages 文件夹中。

注册组件

  • 全局注册:在 app.json 中配置 usingComponents 进行注册,注册后可以在任意页面进行使用。
  • 局部注册:在 pages/*.json 文件中配置 usingComponents 进行注册,注册后只能在当前页面进行使用。

组件样式

一些注意事项:

  • 在自定义的 wxss 文件中,不允许使用标签选择器、id 选择器、属性选择器。
  • 默认情况下,全局样式、组件使用者(组件所在的页面样式)对自定义组件无效。

样式隔离

js
Component({
  options: {
    /**
     * isolate:开启样式隔离
     *          在默认情况下,自定义组件和组件使用者如果存在相同类名,类名不会相互影响。
     *
     * apply-shared:表示组件使用者的 wxss 样式能够影响到自定义组件;但是自定义组件的样式不会影响到组件使用者的样式。
     *
     * shared:表示组件使用者的 wxss 样式能够影响到自定义组件;且自定义组件的样式也会影响到组件使用者的样式。
     *         且其他使用了 apply-shared 以及 shared 的自定义组件也会受到影响。
     */
    styleIsolation: 'isolate',
  },
})

数据和方法

js
Component({
  /**
   * 组件的初始数据
   */
  data: {},

  /**
   * 组件的方法列表
   */
  methods: {},
})

props

html
<custom-component foo="foo"></custom-component>
js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    foo: {
      type: String,
      value: 'foo',
    },
  },
})

emit

html
<custom-component bind:customevent="handleCustomevent"></custom-component>
js
Component({
  methods: {
    handleCustomevent() {
      this.triggerEvent('customevent', 'xxx')
    },
  },
})

侦听器

js
Component({
  properties: {
    label: 'foo'
  }
  data: {
    num: 0,
    count: 0,
    obj: { id: 1, name: 'foo' },
    arr: [1, 2, 3],
  },
  observers: {
    'num': function (newNum) {},
    'count': function (newCount) {},

    // 监听多个属性
    'num, count': function (newNum, newCount) {},

    // 监听对象属性
    'obj.name': function (newName) {},

    // 监听数组子项
    'arr[1]': function (newItem) {},

    // 通配符
    'obj.**': function (newObj) {
      // 此时 newObj 为对象
    },

    // 监听 props
    'label': function (newLabel) {
      // props 的监听器会立即触发
    }
  },
})

插槽

默认插槽

html
<custom-component>Hello World</custom-component>
html
<view>
  <slot></slot>
</view>

启用多 slot 支持

默认情况下,一个组件的 wxml 中只能有一个 slot(默认插槽)。当需要多个 slot 时,需要启用 multipleSlots 选项:

js
Component({
  options: {
    multipleSlots: true,
  },
})

通过为 slot 添加 name 属性来区分不同插槽:

html
<custom-component>
  <view slot="header">header</view>
  <view>body</view>
  <view slot="footer">header</view>
</custom-component>
html
<slot name="header"></slot>
<slot></slot>
<slot name="footer"></slot>

组件实例

html
<custom-component class="child" id="child"></custom-component>
js
Page({
  getChild() {
    const childRef = this.selectComponent('.child')
    console.log(childRef)
  },
})

behavior 逻辑复用

js
const behavior = Behavior({
  // ...
})

export default behavior
js
import behavior from './behavior'

Component({
  behaviors: [behavior],
})

外部样式类

html
<custom-component extend-class="my-class"></custom-component>
css
.my-class {
  color: red;
}
js
Component({
  externalClasses: ['extend-class'],
})
html
<view class="extend-class"></view>

基于 MIT 许可发布