微信小程序> 微信小程序template添加点击事件

微信小程序template添加点击事件

浏览量:708 时间: 来源:wangrcheng

介绍

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/templatetemplate 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的点击事件和传值就实现了。
效果图:

版权声明

即速应用倡导尊重与保护知识产权。如发现本站文章存在版权问题,烦请提供版权疑问、身份证明、版权证明、联系方式等发邮件至197452366@qq.com ,我们将及时处理。本站文章仅作分享交流用途,作者观点不等同于即速应用观点。用户与作者的任何交易与本站无关,请知悉。

产品经理

手机 : 13312967497

擅长 : 小程序流量变现

扫码领取礼包

最新资讯

热门模板

  • 头条
  • 搜狐
  • 微博
  • 百家
  • 一点资讯
  • 知乎