小程序学习--点赞组件(支持复用)

首先看下组件的wxml代码:

<view bind:tap="onlike" class="container">
    <image src="{{like?yesSrc:noSrc}}" />
    <text>{{count}}</text>
</view>

简单说下代码:bind:tap是给这个组件添加一个点击事件onlike 

image标签内的图片是指 点赞时显示的图片 未点赞时显示的图片  

进行三元判断

下面的text标签下 存放的值是点赞的数量值 点了赞 数量+1 取消赞 数量-1

接下来是组件的js代码:

Component({
  /**
   * 组件的属性列表
   */
  properties: {
        //点赞状态
      like:{
        type:Boolean,//类型是布尔型 false或true
        
      },
      count:{
        type:Number//点赞数量 
      },
      
  },

  /**
   * 组件的初始数据
   */
  data: {
     //点赞时的图片 未点赞时的图片
      yesSrc:'images/like.png',
      noSrc:'images/[email protected]'
  },

  /**
   * 组件的方法列表
   */
  methods: {
      // onlike方法,切换喜欢和不喜欢 引进自定义参数 event
      onlike:function(event){
        let like = this.properties.like;
        let count = this.properties.count;
        count = like?count-1:count+1;//like为false数量-1,为true数量+1
        this.setData({
          count: count,//上面的count赋值给这个count
          like:!like
        })
        //激活事件
        let behavior = this.properties.like ? 'like' :'cancel';
        this.triggerEvent('like',{//like为自定义事件名
          behavior: behavior,//behavior赋值
        },{})
      }

  }
})

注释写在代码中...

觉得有用的朋友欢迎点赞,也欢迎相互交流!

猜你喜欢

转载自blog.csdn.net/zhangzeshan/article/details/83781613
今日推荐