index.js:
// components/like/index.js
Component({
/**
* 组件的属性列表
*/
properties: {
like: {
type:Boolean,
},
count: {
type:Number,
}
},
/**
* 组件的初始数据
*/
data: {
yesSrc: 'images/like.png',
noSrc: 'images/like@dis.png'
},
/**
* 组件的方法列表
*/
methods: {
onLike: function(e) {
let count = this.properties.count
let like = this.properties.like
// 根据like值判断count的数值
count = like?count-1:count+1
this.setData({
count,
like:!like
})
// 激活事件
let behavior = this.properties.like ? 'like' : 'cancel'
this.triggerEvent("like", {
behavior
}, {})
}
}
})
index.json:
{
"component": true,
"usingComponents": {}
}
index.wxml:
<!--components/like/index.wxml-->
<view bind:tap="onLike" class='container'>
<image src="{{like?yesSrc:noSrc}}"></image>
<text>{{count}}</text>
</view>
index.wxss:
/* components/like/index.wxss */
.container {
display: inline-flex;
flex-direction: row;
padding-top:10rpx;
}
.container image {
width: 32rpx;
height: 28rpx;
}
.container text {
font-size:24rpx;
line-height: 24rpx;
color:#bbb;
position: relative;
bottom: 10rpx;
left: 6rpx;
}
使用:
classify.wxml:
<v-like bind:like="onLike" like="{{classicData}}" count="{{classicData}}"></v-like>
classify.json:
{
"usingComponents": {
"v-like": "/components/like/index",
}
}
classify.js:
import {ClassModel} from '../../models/classic.js'
import {LikeModel} from '../../models/like.js'
let classic= new ClassModel()
let likeModel = new LikeModel()
Page({
/**
* 页面的初始数据
*/
data: {
classicData:null,
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
classic.getLatest((res)=>{
// 将res中的数据传递到组件中,完成数据的绑定
this.setData({
classicData:res
})
})
},
onLike: function (event) {
console.log(event)
let behavior = event.detail.behavior
// likeModel.like(behavior, this.data.classicData.id, this.data.classicData.type)
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})