码迷,mamicode.com
首页 > 微信 > 详细

微信小程序自定义事件

时间:2018-12-10 14:11:27      阅读:382      评论:0      收藏:0      [点我收藏+]

标签:div   点击事件   rop   按钮组   微信   image   案例   nta   自定义事件   

案例结构

首先,我还是会以案例的形式向大家讲解(这样也能方便大家更好的理解)
简单介绍一下案例项目的内容(以上一章自定义组件的案例为基础)
项目名称:component
自定义子组件cpt
父组件:logs

技术分享图片

在子组件cpt中有一个按钮,按钮上显示的是当前这按钮组件存储的数值counter.

父组件logs引用三个cpt子组件,在父组件有它自己的第一个变量total.

每点击一次不同的按钮都让按钮上的数值不同大小的增加,

同时total变量记录的是三个按钮的数值总和,如图:

技术分享图片

编写子组件

cpt.wxml

<!-- 这是自定义组件的内部WXML结构 -->
<view class="inner">
  <button bindtap="_incrementCounter">{{counter}}</button>
</view>

子组件cpt中有一个按钮,按钮添加点击事件_incrementCounter,同时按钮内容显示的是其数值counter

cpt.js

Component({
  properties: {
    // 这里定义了num属性,属性值可以在组件使用时指定
    num: {          // num定义的就是点击每个按钮分别增加的数值,可以在调用组件的时候进行更改
      type: Number,
      value: 1
    }
  },
  data: {
    // 这里是一些组件内部数据
    counter: 0      // counter定义的是每个按钮上的数值
  },
  methods: {
    // 这里是一个自定义方法,每次点击按钮增加对应的数值
    _incrementCounter (e) {
      let num = this.data.num
      this.setData({
        counter: this.data.counter + num
      })
     // 微信小程序中是通过triggerEvent来给父组件传递信息的
      this.triggerEvent(‘increment‘, {num: num})  // 将num通过参数的形式传递给父组件
    }
  }
})

 

编写父组件

子组件编写完之后,就可以在父组件logs中引用了,并且给它设定自定义事件
(别忘了在父组件的.json文件中进行引用哟)
logs.json

{
  "navigationBarTitleText": "查看启动日志",
  "usingComponents": {
    "component-tag-name": "../components/cpt/cpt"
  }
}

logs.wxml

<!--logs.wxml-->
<view class="container log-list">
  <!-- 以下是对一个自定义组件的引用 -->
   三个按钮总和: {{total}}
  <component-tag-name bind:increment="incrementTotal" num="2"></component-tag-name>
  <component-tag-name bind:increment="incrementTotal" num="3"></component-tag-name>
  <component-tag-name bind:increment="incrementTotal" num="5"></component-tag-name> 
</view>

logs.js

Page({
  data: {
    logs: [],
    total: 0,  // 父组件中的数据total用以记录三个按钮总和
  },
  incrementTotal (e) {    // 定义父组件的
    console.log(e.detail)    // 通过e.detail获取点击的那个对象
    var num = e.detail.num
    this.setData({
      total: this.data.total + e.detail.num
    })
  },
})

分别点击三个按钮时可以看到数值上都有变化的,并且控制台输出的e.detail中也有对应的num属性.

技术分享图片

原文:https://www.jianshu.com/p/9a35a8b961f2

微信小程序自定义事件

标签:div   点击事件   rop   按钮组   微信   image   案例   nta   自定义事件   

原文地址:https://www.cnblogs.com/itxiongwei/p/10095729.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!