小程序组件封装篇-class和插槽使用

组件源码

//wxml
<view class="modal" >
  <view class="cover"></view>
  <view class="default-content-wrapper content-wrapper">
    <slot name="content"></slot>
  </view>
</view>


//js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    showModal: {
      type: Boolean,
      value: false,
    },
  },
  //传入样式
  externalClasses: ['content-wrapper'],
   /**
   * 启用插槽
   */
  options:{
    multipleSlots: true
  },

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

  },

  /**
   * 组件的方法列表
   */
  methods: {
    close() {
      // 使用 triggerEvent 方法触发自定义组件事件,指定事件名、detail对象和事件选项
      this.triggerEvent("close");
    },
  }
})

使用

//json 注册
"usingComponents": {
    "mask-wrapper":"/components/maskWrapper/maskWrapper"
}
//wxml使用
<mask-wrapper content-wrapper="contentWrapper">
  <view class="" slot="content" >
    123
  </view>
</mask-wrapper>

slot使用

  1. 组件内使用slot标签,
  2. 开启slot使用
Component({
    options:{
        multipleSlots: true
    },
})
  1. 页面使用slot,
<mask-wrapper content-wrapper="contentWrapper">
  <view slot="content" >
    123
  </view>
</mask-wrapper>

注:除了第二步,和正常使用slot基本一致

外部class引用

  1. 传入样式,和传参不太一样,需要使用externalClasses接收,类似props写法,[]内部值取决于引用组件时定义的属性名
Component({
    externalClasses: ['content-wrapper'],
})
  1. 组件挂载样式,同普通class类名相同,正常使用即可,content-wrapper
<view class="default-content-wrapper content-wrapper">
    <slot name="content"></slot>
</view>
  1. 外部传入content-wrapper="contentWrapper",这里类似传参
<mask-wrapper content-wrapper="contentWrapper">
  <view class="" slot="content" >
    123
  </view>
</mask-wrapper>

注:

  1. 外部class类名通过传参形式传入组件,组件通过externalClasses接收并冲命名,
    使用重命名之后的类名,在组件内部使用。
  2. 外部引用属性名需要和组件中externalClasses接收值一致
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容