如果对您有帮助,请关注我,加入微信小程序开发交流qq群(173683895)相互交流学习。谢谢
1. include 是引用整个wxml文件,我通常会配合js,css一起使用;
使用场景,需要封装事件和微信 api 的公共模块。
2.template ,模板的引用,引用单个templaye组件,templaye内可以镶入其它组件
使用场景:公共的组件,只负责渲染,可以绑定事件,事件函数需要写在引用它的页面的js
include 示例demo:
<!--pages/model/include.wxml--> <view class='include'> <view style='text-align: center;'>include </view> <view>{{include_data}}</view> <button style='margin-top:30rpx;' bindtap='is_click'>btn_click</button> </view>
js
// pages/model/include.js function init(){ var that =this; //模块内设置data this.setData({ include_data:'include_data' }) // 模块内事件demo this.is_click = function () { // 模块内的引用微信api wx.showToast({ title: '模块内的引用微信api', icon:'none' }) // 模块内逻辑判断 if (that.data.include_data == 'include_data') { that.setData({ include_data: '点击事件后include_data被修改了' }) } else { that.setData({ include_data: 'include_data' }) } } } module.exports={ init:init }
wxss
/* pages/model/include.wxss */ .include{ height: 300rpx; padding: 35rpx; background: cornflowerblue }
在页面引用:
<!--index.wxml--> <!-- include的使用 --> <include src="../model/include"/>
wxss
/**index.wxss**/ @import "../model/include.wxss";
js
//index.js var is_include = require('../model/include.js') Page({ onLoad:function(){ is_include.init.apply(this,[]); } })
apply 作用,让导入的
is_include文件内init函数继承当前页面的page对象。 详细介绍与使用方式
点击打开链接
效果:
template 示例demo
<!--pages/model/model_template.wxml--> <template name='model_template'> <view class='model_template'> <view style='text-align: center;' bindtap='is_click'>template </view> <view>{{demo_data}}</view> <view>{{a}}</view> </view> </template>
wxss
/* pages/model/model_template.wxss */ .model_template{ height: 300rpx; padding: 35rpx; margin-top: 30rpx; background: antiquewhite }
引用页面的写法:
<!--index.wxml--> <!-- template的引用 --> <import src='../model/template.wxml' /> <template is="model_template" data="{{demo_data,...obj}}"/>
wxss
/**index.wxss**/ @import "../model/template.wxss";
js
//index.js Page({ data: { demo_data:'hello template', obj: { a: 'obj_a', b: 'obj_b'} } })
效果图
demo目录结构图: