小程序事件/自定義組件


事件

常見事件:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM