微信小程序点赞效果(点亮小心心)源码一并奉上
首先在components里定义了点赞组件,实现效果:
代码如下:
<!--components/like/index.wxml-->
<view class="container" bindtap="onlike">
<image src="{{like ? yes : no}}"></image>
<text>{{count}}</text>
</view>
/* components/like/index.wxss */
.container {
display: inline-flex;
flex-direction: row;
padding: 10rpx;
width: 190rpx;
}
/* 后代选择器 ,注意这里是可能报错的*/
.container image {
width: 66rpx;
height: 66rpx;
}
.container text {
font-size: 36rpx;
color: rgb(61, 43, 43);
position: relative;
left: 0rpx;
bottom: 15rpx;
}
/* 屏幕iphone5 的尺寸320*568,那么在高度上rpx会分成568份,每份一个rpx,此时1rpx=1px*/
// components/like/index.js
const app = getApp()
Component({
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
count: 999,
yes: '/components/like/img/like.png',
no: '/components/like/img/dislike.png',
like: false
},
/**
* 组件的方法列表
*/
methods: {
onlike() {
let like = this.properties.like;
let count = this.properties.count;
count = like ? count - 1 : count + 1;
console.log('count like')
this.setData({
count,
like:!like
})
}
}
})
然后报错:
Some selectors are not allowed in component wxss
自定义组件
App 提示:
Some selectors are not allowed in component wxss, including tag name selectors, ID selectors, and attribute selectors.
后来看了别人的文章,改scss,且在微信文档找到了答案。
将css代码改成:
/* components/like/index.wxss */
.container {
display: inline-flex;
flex-direction: row;
padding: 10rpx;
width: 190rpx;
}
/*改为正常的css选择器名字*/
image {
width: 66rpx;
height: 66rpx;
}
text {
font-size: 36rpx;
color: rgb(61, 43, 43);
position: relative;
left: 0rpx;
bottom: 15rpx;
}
/* 屏幕iphone5 的尺寸320*568,那么在高度上rpx会分成568份,每份一个rpx,此时1rpx=1px*/
别忘了,usingcomponents