当前位置:   article > 正文

【小程序】微信小程序自定义组件Component详细总结_微信小程序 component

微信小程序 component

1- 前言


在本文中你将收获

  1. 小程序如何使用自定义组件
  2. 自定义组件之间的传值
  3. 自定义组件中插槽的使用

2- 组件文件新建

2.1 定义组件

根目录新建components文件夹,建立cell 文件夹,右击创建cell的Component组件

  • cell.js
  • cell.wxml
  • cell.json
  • cell.wxss

2.2 注册组件

页面的xxx.json ,usingComponent注册

"usingComponents": {
"item":"/components/item/item"
}
  • 1
  • 2
  • 3

2.3 使用组件

<item></item>
  • 1

2.4 图参考

在这里插入图片描述
在这里插入图片描述

3- 外部类和样式隔离

3.1定义组件

  • cell.wxml 文件
<view class="cell cell-class">
</view>
  • 1
  • 2
  • cell.wxss
/* pages/com/com.wxss */
.cell{
  color: tomato;
}
.mycell{
  color: #f70;
  line-height: 120rpx !important;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • cell.js 文件
  /* 选项 */
  options:{
    /* 样式隔离:apply-shared 父影响子
    shared 父子相互影响   isolated 相互隔离
    */
    styleIsolation:'isolated',
  },
  //通过组件的外部类实现父组件控制自己的样式
  externalClasses:["cell-class"],
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

3.2 使用组件

<cell></cell>
<cell cell-class="mycell"></cell>
  • 1
  • 2

在这里插入图片描述

3.3 图解释

在这里插入图片描述

4- 组件插槽

4.1 默认插槽

  • cell.wxml
 <view class="cell">
  我是cell组件
  <slot></slot>
</view>
  • 1
  • 2
  • 3
  • 4
  • cell.js
  /* 选项 */
  options:{
    //允许多个插槽
    multipleSlots:true,
  },
  • 1
  • 2
  • 3
  • 4
  • 5
  • cell.wxss
.cell{
  height: 88rpx;
  line-height: 88rpx;
  border-bottom: 1rpx solid #cccccc;
}
  • 1
  • 2
  • 3
  • 4
  • 5
使用cell组件
<cell>
  <text>放假</text>
  <text>快点到来</text>
</cell>
  • 1
  • 2
  • 3
  • 4

在这里插入图片描述

4.2 命名多插槽

  • cell.wxml
 <view class="cell cell-class">
  <slot name="pre"></slot>
  我是cell组件
  <slot></slot>
  <slot name="next"></slot>
</view>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • cell.js
  /* 选项 */
  options:{
    //允许多个插槽
    multipleSlots:true,
  },
  • 1
  • 2
  • 3
  • 4
  • 5
  • cell.wxss
.cell{
  height: 88rpx;
  line-height: 88rpx;
  border-bottom: 1rpx solid #cccccc;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • com.wxml
<!-- 插槽 -->
<cell>
  <text slot="pre">声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读