1 <template name="demo"> 2 <view class='tempDemo'> 3 <text class='name'>FirstName: {{firstName}}, LastName: {{lastName}}</text> 4 <text class='fr' bindtap="clickMe" data-name="{{'Hello! I am '+firstName+' '+LastName+'!'}}"> clcikMe </text> 5 </view> 6 </template>
3. 样式文件:html
模板拥有本身的样式文件(用户自定义)。json
1 /* templates/demo/index.wxss */ 2 .tempDemo{ 3 width:100%; 4 } 5 view.tempDemo .name{color:darkorange}
4. 页面引用:小程序
page.wxml微信小程序
1 <!--导入模板--> 2 <import src="../../templates/demo/index.wxml" /> 3 <!--嵌入模板--> 4 <view> 5 <text>嵌入模板</text> 6 <template is="demo" data="{{...staffA}}"></template><!--传入参数,必须是对象--> 7 <template is="demo" data="{{...staffB}}"></template><!--传入参数,必须是对象--> 8 <template is="demo" data="{{...staffC}}"></template><!--传入参数,必须是对象--> 9 </view>
page.wxss微信
1 @import "../../templates/demo/index.wxss" /*引入template样式*/
page.jsapp
1 Page({ 2 /** 3 * 页面的初始数据 4 */ 5 data: { 6 staffA: { firstName: 'Hulk', lastName: 'Hu' }, 7 staffB: { firstName: 'Shang', lastName: 'You' }, 8 staffC: { firstName: 'Gideon', lastName: 'Lin' } 9 }, 10 clickMe(e) { 11 wx.showToast({ title: e.currentTarget.dataset.name, icon: "none", duration: 100000 }) 12 } 13 ...... 14 })
备注:xss
一个模板文件中能够有多个template,每一个template均需定义name进行区分,页面调用的时候也是以name指向对应的template;ide
template模板没有配置文件(.json)和业务逻辑文件(.js),因此template模板中的变量引用和业务逻辑事件都须要在引用页面的js文件中进行定义;工具
template模板支持独立样式,须要在引用页面的样式文件中进行导入;组件化
页面应用template模板须要先导入模板 <import src="../../templates/demo/index.wxml" /> ,而后再嵌入模板 <template is="demo" data="{{...staffA}}"></template>
二. Component组件:
1. 组件建立:
新建component目录——建立子目录——新建Component;
2. 组件编写:
新建的component组件也由4个文件构成,与page相似,可是js文件和json文件与页面不一样。
js代码:
1 // components/demo/index.js 2 Component({ 3 /** 4 * 组件的属性列表 5 */ 6 properties: { 7 name: { 8 type: String, 9 value: '' 10 } 11 }, 12 13 /** 14 * 组件的初始数据 15 */ 16 data: { 17 type: "组件" 18 }, 19 20 /** 21 * 组件的方法列表 22 */ 23 methods: { 24 click: function () { 25 console.log("component!"); 26 } 27 } 28 })
json配置文件:
1 { 2 "component": true, 3 "usingComponents": {} 4 }
3. 组件引用:
页面中引用组件须要在json配置文件中进行配置,代码以下:
1 { 2 "navigationBarTitleText": "模板demo", 3 "usingComponents": { 4 "demo": "../../components/demo/index" 5 } 6 }
而后在模板文件中进行使用就能够了,其中name的值为json配置文件中usingComponents的键值:
1 <demo name="comp" /> 2 <!--使用demo组件,并传入值为“comp”的name属性(参数)-->
这样就能够了。
PS:组件中不会自动引用公共样式,若是须要则需在样式文件中引入:
1 @import "../../app.wxss";
我的原创博客,转载请注明来源地址:http://www.javashuo.com/article/p-unxlfhrg-eu.html