创建存放组件的components
文件夹,在components
下新建组件like
文件夹,然后新建component
,index.js
、index.json
、index.wxml
、index.wxss
文件。
在页面的配置文件index.json
中引入组件:
{
"usingComponents": {
"v-like":"components/like/index"
},
"navigationBarTitleText": "首页"
}
之后,在index.wxml
中使用组件<v-like />
。
在
app.wxss
中设置全局的样式,其中page
默认是全局元素,对它进行设置类似于对body
设置样式。
组件可以继承全局样式中的font-*
、color
属性,其他的不继承。
页面可以继承绝大部分全局样式。
消除文字空白间距
.container image {
width: 36rpx;
height: 24rpx;
font-size: 24rpx;
/* 文字自身存在空白间距,消除间距 */
line-height: 24rpx;
/* 相对定位 */
position: relative;
left: 6rpx;
bottom: 10rpx;
}
flexbox
的display
自身的取值:flex
,inline-flex
,Safari的webkit内核浏览器,必须加上display: -webkit-flex;
使用bindtap
绑定处理事件,在组件下index.js
文件的methods
内写事件方法。
<view bind:tap="isLike" class="container">
<view catch:tap="isLike" class="container">
bind
事件绑定,不会阻止冒泡事件向上冒泡。catch
事件绑定,可以阻止冒泡事件向上冒泡。
properties
属性组件的属性列表
<view bind:tap="isLike" class="container">
<text>{{count}}</text>
</view>
properties: {
like: {
// 必填
type: Boolean,
// 下面的内容选填
value: false, //默认值
observer: function() {
}
},
count: {
type: Number
}
}
组件的方法列表
methods: {
isLike: function(e) {
let like = this.properties.like;
let count = this.properties.count;
count = like ? like - 1 : like + 1;
this.setData({
count: count,
like: !like
})
}
}
可以将页面内的功能模块抽象成自定义组件,以便在不同的页面中重复使用;也可以将复杂的页面拆分成多个低耦合的模块,有助于代码维护。
使用postman测试调用数据API。