组件传参

@Parameter

父组件 → 子组件

- 简化声明 - 类型 type;不需要默认值
[] 封装空组件 emptyCom
[] 封装图片轮播组件 my-swiper
. 不同的轮播组件在不同的页面显示的图片列表和高度不一样;通过传递图片列表参数 imgs 和高度参数h,采用内联样式设置轮播组件高度
  1. 创建组件 my-swiper
  2. 组件逻辑js - 声明2个参数,高度默认20,图片列表为空
  3. Component({
        properties: {
            h:{
                type:Number,
                value: 20
            },
            imgs: {
                type: Array,
                value: []
            }
        }
    })
  4. 组件结构 wxml - 内联样式 style 不需要使用{}
  5. <swiper class="swiper" style="height: {{h}}vh;"  indicator-dots indicator-color="#fff" indicator-active-color="#f40" autoplay circular>
        <swiper-item wx:for='{{imgs}}' wx:key='id'>
            <image class="img" src="{{item.url}}" mode="aspectFill"></image>
        </swiper-item>
    </swiper>
  6. 组件样式 wxss - 轮播图高度由内联样式 style 指定;这里仅需指定图片大小
  7. .img{
        width: 100%;
    }
  8. 父组件配置 json - 引入
  9. {
        "usingComponents": {
            "my-swiper": "../../components/my-swiper/my-swiper"
        }
    }
  10. 父组件结构 wxml - 使用;传递高度h;绑定图片列表 imgs
  11. <my-swiper h='{{25}}' imgs='{{imgs}}'></m-swiper>
  12. 父组件逻辑 js - 在页面的 onLoad() 中从 大树小站 请求图片,或自行准备;imgs 是 data 中的定义的数据
  13. wx.request({
        url: 'https://glpla.github.io/utils/data/swiper.json',
        success: res => {
            console.log('res', res);
            this.setData({
                imgs: res.data.cont
            })
        }
    })
[] 封装阿里字体图标组件 my-iconfont
. 父组件仅仅传递图标类,控制组件显示相应的字体图标
  1. 创建子组件
  2. 右键单击组件根目录 components → 新建组件目录 my-iconfont

    再右键组件目录,新建 Component 为 my-iconfont;组件名和组件目录通常保持一致

  3. 设计子组件
  4. wxml:基类 iconfont 保留,不同的图标类 icon 通过父组件传递获取

    <text class="iconfont {{icon}}"></text>

    js:在属性 properties 中设置将图标类 icon 的类型和默认值;并允许添加全局类

    Component({
        options: {
            addGlobalClass: true,
        },
        properties: {
            icon:{
                type:String
            }
            //简化形式icon:String
        }
    })
  5. 父组件 - 引入组件
  6. 在使用组件的页面 .json 中配置

    {
        "usingComponents": {
            "my-iconfont":"../../components/my-iconfont/my-iconfont"
        }
    }

    父组件 - 使用组件

    在使用组件的 .wxml 中,将图标类作为属性指定给参数接口即可

    <my-iconfont icon='icon-home'></my-iconfont>

子组件 → 父组件

采用事件绑定

  1. 子组件绑定传统事件并在事件处理函数中 触发|发送|triggerEvent 自定义事件给父组件,可以指定传递的参数
  2. 父组件绑定自定义事件并声明事件处理函数