小程序封装组件

需求: 在一个项目中我们会发现有很多的共同样式 ;所以我们如果想优化代码就得自己封装组件:

子组件: 

在根目录上建立一个components的文件夹,在里面自定义一个文件如:infocell

index.json

{
  "component": true,//是否使用组件
  "usingComponents": {}//引入组件,这里做为子组件为父组件使用,暂时不需要引入其它子组件,所以可以不写
}

index.wxml

<view class='payWrap'>
  <text class='title'>{{title}}</text>
  <text class='desc'>{{desc}}</text>
  <text class='icon' bindtap='popView'>...</text>
</view>

index.js

// components/infocell/index.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    // 左侧标题
    title: { // 属性名
      type: String, // 类型(必填),目前接受的类型包括:String, Number, Boolean, Object, Array, null(表示任意类型)
      value: '' // 属性初始值(可选),如果未指定则会根据类型选择一个
    },
    desc: {
      type: String,
      value: ''
    }
  },

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

  },

  /**
   * 组件的方法列表
   */
  methods: {
    popView: function () {
      // 注册点击事件传给父组件
      this.triggerEvent('popView')
    }
  }
})

父组件引入infocell子组件:

detail文件下的index.json

{
  "usingComponents": {
//infocell为自定义命名,冒号后为子组件的路径
    "infocell": "/components/infocell/index",
  }
}

detail文件下的index.wxml

标签为json中自定义的属性名

bind:popView的点击事件为Infocell传递过来的点击事件名(popView)绑定的popView要和子组件一样

<infocell title='支付' desc='{{baitiaoSelectItem.desc}}'     bind:popView='popBaitiaoView'></infocell>

detail文件下的index.js

给组件赋值:

Page({

  /**
   * 页面的初始数据
   */
  data: {
    hideBaitiao: true, // 是否隐藏白条的遮罩
    baitiaoSelectItem: {
      desc: "【白条支付】首单享立减优惠"
    },
  },
  /**
   * 显示白条弹框
    使用子组件传递过来的事件
   */
  popBaitiaoView: function () {
    this.setData({
      hideBaitiao: false
    })
  },
  
})

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

周家大小姐.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值