企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
1.新建一个组件:新建一个components文件夹 ->再建一个组件文件夹 ->右键:新建component 2.组件接收的值,以及设置默认值 ``` properties: { title:{ type : String, //类型 value : "默认标题", //默认值 }, }, ``` 3.在需要用到的文件中的json中引入 ``` "usingComponents": { "header" : "/components/header/index" } ``` 4.wxml中使用 ``` <view> <header title="推荐歌曲"><view>222</view></header> </view> ``` **案例:封装一个头部组件,右侧内容可能有也可能没有,方案一:再定义一个变量控制右侧显示** **重点学习**:方案二:使用css的伪类(empty)和“+”连接符去动态控制元素显示隐藏 问题:小程序中使用插槽,如果你有默认的内容,再传了插槽的内容进去,和vue不同的是两个都会显示出来(vue中默认的内容将不显示), ``` <!--components/header/index.wxml--> <view class="header"> <view class="title">{{title}}</view> <!-- 右侧内容 --> <view class="right" wx:if="{{showRight}}"> <!-- 插槽内容 --> <view class="slot"> <slot></slot> </view> <!-- 默认显示内容 --> <view class="defult"> <text>{{rightTitle}}</text> <image class="icon" src="/assets/images/jiantou.png"></image> </view> </view> </view> ``` ![](https://img.kancloud.cn/ab/d3/abd37fb5dfd4dd280410fb0dc174c838_554x89.png) ```/* 判断当.solt这个类下面的元素是空的时候(也就是没有使用插槽,使用‘+’连接符,给.defult这个类设置样式) */ .header .slot:empty + .defult{ display: flex; } .header .defult{ /* 默认不显示 */ display: none; align-items: center; font-size: 28rpx; color: #777; } ``` 效果: 1.当插槽没有内容时,默认显示的更多 ``` <view> <header title="推荐歌曲"></header> </view> ``` ![](https://img.kancloud.cn/89/73/89737986990d966671a3992cd894c204_579x58.png) 2.当有插槽内容时,显示的是插槽的内容 ``` <view> <header title="推荐歌曲"> <view>插槽内容</view> </header> </view> ``` ![](https://img.kancloud.cn/08/52/0852d356cd2f4dba8dc158a3d7557fe6_566x55.png) ***** 拓展:vue中使用插槽 ``` 组件 <template> <div> <slot> <div>我是默认内容</div> </slot> </div> </template> ``` 引入后没有传内容,显示的是默认的 ![](https://img.kancloud.cn/3a/da/3ada4e5aeb615e1f8b1700fe2184abb2_186x71.png) ``` 组件中传内容 <ceshi> <div>我是修改后的内容</div> </ceshi> ``` ![](https://img.kancloud.cn/31/f8/31f86e1490004508437dffe31f4c070e_214x61.png)