微信小程序自定义组件Component的代码详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

微信小程序自定义组件Component的代码详解

前端小媛   2023-03-23 我要评论

1- 前言

在本文中你将收获

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

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"
}

2.3 使用组件

<item></item>

2.4 图参考

3- 外部类和样式隔离

3.1定义组件

cell.wxml 文件

<view class="cell cell-class">
</view>

cell.wxss

/* pages/com/com.wxss */
.cell{
  color: tomato;
}
.mycell{
  color: #f70;
  line-height: 120rpx !important;
}

cell.js 文件

  /* 选项 */
  options:{
    /* 样式隔离:apply-shared 父影响子
    shared 父子相互影响   isolated 相互隔离
    */
    styleIsolation:'isolated',
  },
  //通过组件的外部类实现父组件控制自己的样式
  externalClasses:["cell-class"],

3.2 使用组件

<cell></cell>
<cell cell-class="mycell"></cell>

3.3 图解释

4- 组件插槽

4.1 默认插槽

cell.wxml

 <view class="cell">
  我是cell组件
  <slot></slot>
</view>

cell.js

  /* 选项 */
  options:{
    //允许多个插槽
    multipleSlots:true,
  },

cell.wxss

.cell{
  height: 88rpx;
  line-height: 88rpx;
  border-bottom: 1rpx solid #cccccc;
}

使用cell组件

<cell>
  <text>放假</text>
  <text>快点到来</text>
</cell>

4.2 命名多插槽

cell.wxml

 <view class="cell cell-class">
  <slot name="pre"></slot>
  我是cell组件
  <slot></slot>
  <slot name="next"></slot>
</view>

cell.js

  /* 选项 */
  options:{
    //允许多个插槽
    multipleSlots:true,
  },

cell.wxss

.cell{
  height: 88rpx;
  line-height: 88rpx;
  border-bottom: 1rpx solid #cccccc;
}

com.wxml

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们