小程序组件化——模板与事件

模板template绝对是小程序中除“组件”以外最好用的机制了。

笔者在前文中曾经提到过,小程序template不能写js,当时说 —— 究其原因,也不过是“template内容还是Page中的一部分”罢了。

但随着小程序的发展,这一功能也早就得到了突破 --> es6

事件绑定
模板文件不仅支持传入状态,还可以传入事件。我们在Page中定义一个onClick事件:

Page({
	data:{
		message:'你好,笑晨',
		itemData:{
			message:'Hello Xiaochen'
		}
	},
	onClick(event){
		console.log(event.currentTarget.dataset,this);
	}
});

然后修改index.wxml:

<import src="item.wxml" />
<template is="item1" data="{{obj:itemData,tips:'this is a tip',onClick}}" />

这里我们将onClick作为一个属性传入,之后就可以在item.wxml中接收,
并绑定事件:

<template name="item1">
	<text style="color:red;">{{obj.message}}</text>
	<view>{{tips}}</view>
	<button bindtap="onClick" data-inc="{{tips}}">点我</button>
</template>

这里我们通过bindtap绑定了onClick事件,然后通过data-inc绑定参数,在onClick中我们通过event.currentTarget.dataset获取data-inc参数值:

{inc:"this is a tip"}

同时,onClick中的this指向Page对象,这个需要特别注意。实际开发中并不建议将onClick直接写在Page中,我们可以创建一个item.js来存储和item.wxml有关的事件:

export default{
	onClick:function(event){
		console.log(event.currentTarget.dataset.inc);
	}
}

然后将item.js集成到index.js中:

import item from './item.js'

Page({
	data:{
		message:'你好,笑晨',
		itemData:{
			message:'Hello Xiaochen'
		}
	},
	...item
})

这样做起来会更加便于维护。

发布了195 篇原创文章 · 获赞 391 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_43624878/article/details/103402510