创建自定义组件
- 在项目根目录新建文件夹 CustomComponents
- 在 CustomComponents 目录内为 每个自定义组件 单独新建一个文件夹,例如: headerTab
- 右键 headerTab 文件夹,选择"新建 Component",自动生成.json、.js、.wxml、.wxss四个子文件
如何在一个界面中使用 自定义组件
在 界面对应的 json 文件中,配置子视图路径,完成后即可将子视图作为一个类似View的组件来使用
{
"usingComponents": {
"headerTab":"/CustomComponents/headerTab/headerTab"
}
}
自定义组件生命周期
Component({
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的生命周期函数
*/
lifetimes: {
/// 组件实例刚刚被创建好。此时还不能调用 setData
created() {
},
/// 组件完全初始化完毕、进入页面节点树后。绝大多数初始化工作可以在这个时机进行
async attached() {
const res = await this.loadTabData()
this.setData ({
list:res,
selIndex:0,
})
console.log(this.data.selIndex)
},
/// 在组件离开页面节点树后
detached() {
}
},
/**
* 组件的方法列表
*/
methods: {
loadTabData() {
return new Promise((resole,reject)=>{
wx.request({
url: 'https://api.imooc-blog.lgdsunday.club/api/hot/tabs',
success: (res)=>{
const statusCode = res.statusCode
if (statusCode == 200) {
resole(res.data.data.list)
}else {
reject(res.errMsg)
}
},
fail:(error)=>{
console.log('网络请求失败' + error)
reject(error)
}
})
})
},
}
})
设置可滚动视图
<!--
.wxml 内
1. scroll-x 设置滚动方向,默认true
2. 组件+wx:for,可以批量创建组件,也可以用block包裹
3. 可选样式语法tab、selTab:class="tab {{selIndex === index ? 'selTab':''}}"
-->
<scroll-view scroll-x class="tabs-box">
<view wx:for="{{list}}" wx:key="index" class="tab {{selIndex === index ? 'selTab':''}}" bind:tap="selIndex" data-index="{{index}}">{{item.label}}{{index}}
</view>
</scroll-view>
/* .wxss 内 */
tabs-box {
/* 指定宽度 + 不换行 */
width: 750rpx;
white-space: nowrap;
border-bottom: 1px solid #cccccc;
}
/* CSS 样式的优先级是由选择器的特殊性和顺序决定的。简单的解释就是默认样式放前面 */
.tab {
color: salmon;
/*
1、可以将块级元素(例如 <View> )转换为内联元素,从而可以让它们和其他元素在同一行内显示
2、使用 display: inline; 样式会将元素的 width、height、margin-top、margin-bottom 和 float 属性失效。这是因为内联元素不支持这些属性
*/
display: inline;
padding: 10px;
}
.selTab {
color: royalblue;
}
网友评论