小程序自定义组件的两种方式

一:!(通过定义id,采取selectComponent选择调用)

component

wxml:

<view class='wx_dialog_container' hidden="{{!isShown}}">
    <view class='wx-mask'></view>
    <view class='wx-dialog'>
        <view class='wx-dialog-title'>{{ title }}</view>
        <view class='wx-dialog-content'>{{ content }}</view>
        <view class='wx-dialog-footer'>
            <view class='wx-dialog-btn' catchtap='_cancelEvent'>{{ cancelText }}</view>
            <view class='wx-dialog-btn' catchtap='_confirmEvent'>{{ confirmText }}</view>
        </view>
    </view>
</view>

js:

Component({

  options: {
    multipleSlots: true // 在组件定义时的选项中启用多slot支持
  },

  /**
   * 组件的属性列表
   */
  properties: {
    // 弹窗标题
    title: {            // 属性名
      type: String,     // 类型(必填),目前接受的类型包括:String, Number, Boolean, Object, Array, null(表示任意类型)
      value: '标题'     // 属性初始值(可选),如果未指定则会根据类型选择一个
    },
    // 弹窗内容
    content: {
      type: String,
      value: '弹窗内容'
    },
    // 弹窗取消按钮文字
    cancelText: {
      type: String,
      value: '取消'
    },
    // 弹窗确认按钮文字
    confirmText: {
      type: String,
      value: '确定'
    },
    // 是否显示Dialog
    isShown: {
      type: Boolean,
      value: false
    }
  },

  /**
   * 私有数据,组件的初始数据
   * 组件的初始数据
   */
  data: {
    title:'默认标题',
    content:'默认内容',
    // 弹窗显示控制
    isShow: false
  },

  /**
   * 组件的方法列表
   *
   */
  methods: {
    _cancelEvent() {
      //触发取消回调
      this.triggerEvent("cancelEvent")
    },
    _confirmEvent() {
      //触发成功回调
      this.triggerEvent("confirmEvent");   //confirmEvent由调用方声明和定义,在调用方 bind:confirmEvent 来声明,在js中定义函数
    }
  }
})

page引用:

wxml:

 <dialog title='新的启航'
          content='启航个啥,站住!'
          cancelText='取消'
          confirm='确定'
          isShown="{{isShown}}"
          bind:cancelEvent="cancel"
          bind:confirmEvent="confirm"/>
  <button type="primary" bindtap="showDialog"> ClickMe! </button>

js:

 data: {
    isShown: false
  },

showDialog() {
  this.setData({
    isShown: true
  })
},
cancel(e) {
  console.log('你点击了取消');
  //do something when cancle is clicked
  this.setData({
    isShown: false
  })
},

confirm(e) {
  console.log('你点击了确定');
  ////do something when sure is clicked
  this.setData({
    isShown: false
  })
},

json

{
  "navigationBarTitleText": "首页",
   "usingComponents": {
     "dialog": "../../component/dialog/dialog"
   }
}

-----selectComponent方法后期补充

原文地址:https://www.cnblogs.com/vonson/p/10694839.html