zoukankan      html  css  js  c++  java
  • 小程序事件/自定义组件

    事件

    常见事件:

    test.wxml     

    <!-- 事件-->
    <button bind:tap="click" data-name="{{b}}" data-age="sb">按钮</button>   #bind:事件名="事件函数名"
    <view class="outer" bind:tap="click1" data-name="1">
    外面
    <view class="inner" bindtap="click2" data-name="2">    
    里面
    </view>
    </view>

    test.js   (在js最下方写)

     click1: function () {
    
        console.log("外面的")
      },
       click2: function () {
     
        console.log("中间的")
      }

    事件传递参数:(重点******)

    当视图层发生事件时,某些情况需要事件携带一些参数到执行的函数中,这个时候可以通过 data-属性 来完成

    1.格式:data-属性的名称

    2.获取:e.currentTarget.dataset.属性的名称       (除了currentTarget还有Target)

    自定义组件

    1.创建自定义组件

    类似于页面,一个自定义组件由 json 、wxml 、wxss 、js 4个文件组成

    声明组件

    首先需要在 json 文件中进行自定义组件声明

    {
      "component": true,
    }

    注册组件

    在自定义组件的js文件中,需要使用component()来注册组件,并提供组件的属性定义、内部数据和自定义方法

    Component({
      /**
       * 组件的属性列表
       */
      properties: {
        name: {
          type: String,
          value: "你好"
        }
      },
    
      /**
       * 组件的初始数据
       */
      data: {
        title:"ssss"
      },
    
      /**
       * 组件的方法列表
       */
      methods: {
        click:function(e){
          this.triggerEvent("icre", { "index": 323 }, {})  #注意一定要写这个,icre相当于触发事件,可以通过icre知道使用自定义组件,后面的index是传的值
        }
      }
    })

    自定义组件一般都创建commpents,然后再右击这个目录选择创建commpent,重命名

    2.使用自定义组件

    首先要在需要使用的json文件中进行引用声明

    比如在test下使用,那么在test.json中先写

     3.组件将事件传给页面

    组件的wxml  (设置一个按钮,绑定一个事件click,点击按钮就加1)

    <button bind:tap="click"  data-ss="123">按钮</button>

    组件的js    (在methods中写事件函数)

    methods: {
        click:function(e){
          console.log(e)
          this.triggerEvent("icre", { "index": 323 }, {})  #这里的icre相当于是给使用标记的页面做个标记,后面跟的是参数index
        }
    
      }

    页面    

    <view></view>
    {{num}}
    <tes name="是的" bind:icre="click"></tes>  #通过icre和自定义组件绑定

    页面js

    click:function(e){    #click事件函数,自定义组件的按钮点击一次数字就加1
        console.log(e)    
          this.setData({
            num:this.data.num+1
          })
      }

    自定义组件中传递的index参数,在页面js中console.log(e)中detail

  • 相关阅读:
    进程与线程
    the art of seo(chapter seven)
    the art of seo(chapter six)
    the art of seo(chapter five)
    the art of seo(chapter four)
    the art of seo(chapter three)
    the art of seo(chapter two)
    the art of seo(chapter one)
    Sentinel Cluster流程分析
    Sentinel Core流程分析
  • 原文地址:https://www.cnblogs.com/wangcuican/p/11800414.html
Copyright © 2011-2022 走看看