微信小程序 template添加點擊事件


 

介紹
template是微信小程序提供的模板,可以在模板中定義代碼片段,然后在不同的地方調用。

簡單使用
定義template
因為項目中可能會需要到不止一個template,所以最好新建一個文件夾來存放template相關的文件。注意這里只是單獨的創建各個文件,並不是創建Page或者Component.
創建好之后的文件目錄如圖:

這里演示一個用template當列表的item,然后可以點擊並獲取到值。 
然后開始寫templates.wxml文件,這里面可以有多個template代碼塊,如代碼所示:

<!--列表頁item  -->
<template name="template01">
  <view class='item' bindtap='onclick' data-item='{{item}}'>
    {{item}}
  </view>
</template>

<template name="template02">
  <view>
    this is template02 and nothing to do
  </view>
</template>

可以看出template和普通的標簽定義差不多,但是每個template必須為它設置name,因為在使用的時候可以是根據這個name的值來找到對應關系的。

然后開始布局,templates.wxss文件代碼:

.item{
  background: beige;
  padding: 10px;
  display: flex;
  flex: 1;
  justify-content: center;
  align-items: center;
  margin: 20px 10px 10px 10px
}

最后完成template里面的邏輯事件,templates.js文件代碼:

var temp = {
  onclick: function (event) {
    console.log("點擊了" + event.currentTarget.dataset.item)
  }
}
//導出,供外部使用
export default temp

使用template

經過上面幾步template的定義工作就基本完成了,下面開始具體的使用,首先在需要使用template的文件中引入templates.wxml文件,list.wxml文件的具體代碼:

<!--引入wxml文件  -->
<import src="../templates/templates.wxml"/>

<view wx:for="{{arrys}}" wx:key="">
  <view class='item' bindtap='itemclick' data-item='{{item}}'>
    <!--和普通標簽一樣使用,is對應的是templates中的name  data是傳入template值  -->
    <template is="template01" data="{{item}}"/>
  </view>
</view>

然后在list.wxss中引入template中用到的樣式。

@import "../templates/templates.wxss";

最后在list.js中引入templates的js文件:

import templates from '../templates/templates'

到這里templates作為列表的item就可以顯示了,那具體的點擊事件是怎么處理的呢? 
我們看這一段:

<view class='item' bindtap='itemclick' data-item='{{item}}'>
    <!--和普通標簽一樣使用,is對應的是templates中的name  data是傳入template值  -->
    <template is="template01" data="{{item}}"/>
</view>

給template的外層view設置了一個點擊事件,點擊事件的具體代碼:

  itemclick(event){
    templates.onclick(event)
  }

其實外層view的點擊事件自己什么也沒做,只是調用了template中的點擊事件onclick,並且把當前事件傳遞給了它。

  onclick: function (event) {
    console.log("點擊了" + event.currentTarget.dataset.item)
  }

這樣template的點擊事件和傳值就實現了。 
效果圖:

 

 

 

 

 

轉 : https://blog.csdn.net/wangcheng_/article/details/79764584

 


免責聲明!

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



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