微信小程序实现组件化传参

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 () {
    
  }
})

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值