首页 > 微信 > 详细

微信小程序模板(template)和组件的区别

时间:2019-12-17 21:09:21      阅读:131      评论:0      收藏:0      [点我收藏+]

 template模块主要是展示,方法需要在使用template的页面中定义,对于通用的数据,最先想到或者理应是template,但是template有个缺点,那就是只是页面效果,不会有对应的js操作。

  而component组件,则拥有自己的js文件,整个component组件类似一个page页面。简单来说,只是展示用,建议使用template,组件中涉及到较多的逻辑,建议使用component。

  一、template模块

  定义模板,一份template.wxml文件中能写多个模板,用name区分
 

<template name="easy">
<text class=‘red‘ bindtap="click">I‘m Easy,{{hello}}</text> //注意:1、这里有个点击事件。2、{{hello}}是使用模板时传入的属性(参数)
</template>
 
<template name="Davi">
<text>I‘m Davi,nice to meet you</text>
</template>

 

  在页面中引入并使用模板

<!--index.wxml-->
//导入模板
<import src="../../template/template.wxml" />
 
<view class="container">
<!-- 引用template模板,用is="easy"的方式,选择模板 -->
<template is="easy" data="{{...str}}" /> //传入参数,必须是对象
<template is="Davi" />
</view>

 

  在页面中引入模板样式。模板拥有自己的样式文件(用户自定义),只需要在使用页面的wxss文件中引入即可
 

/**index.wxss**/
@import "../../template/template.wxss"; //引入template样式
.container{
display:flex;
}

 

  由于template中没有js文件,因此template中的点击事件,在使用页面中的js里定义。如上,name=easy的模板有个点击事件click,则click方法,需要在index.js中定义

//index.js
Page({
data: {
str:{
hello:”nice to meet you“
}
},
click:function(){
console.log("click Easy");
}
})

 

  因为template没有自己的js文件,所以在列表中涉及到列表子项独立的操作,建议将列表子项写成component。

  二、component组件

  小程序组件文档:https://mp.weixin.qq.com/debug/wxadoc/dev/framework/custom-component/

  创建一个component,只需要在其目录下右键--新建--component,即可直接生成4个文件(json中的设置会默认"component": true)。component组件的结构和page的结构类似,都是有js、wxml、wxss、json四类文件组成。wxss代码与page是一样的,代码就不贴了。其他代码如下:

  wxml代码,与page一样

<!--components/hello/hello.wxml-->
<text class="red" bindtap="click">component {{type}} hello {{name}}</text>

 

  js代码,与page有些许不同
 

// components/hello/hello.js
Component({
/**
* 组件的属性列表,使用组件时,传入的参数
*/
properties: {
name:{
type:String,
value:‘‘
}
},
 
/**
* 组件的初始数据,组件内部的数据
*/
data: {
type:"组件"
},
 
/**
* 组件的方法列表,组件内部的方法
*/
methods: {
click:function(){
console.log("easy");
}
}
})

 

  json代码,需要注明"component": true,表示这是一个组件
 

// components/hello/hello.json
{
"component": true,
"usingComponents": {}
}

 

  page中的使用,与template模板不同,component不需要在wxml中引入,但需要在json中指明使用的组件名及路径。
 

<!--index.wxml-->
<view class="container">
<hello name="Easy"/> //使用hello组件,并传入值为“Easy”的name属性(参数)
</view>

 

//index.json
{
"usingComponents":{
"hello":"/components/hello/hello" //前面的hello是组件名,可以更改。路径指向使用的组件
}
}

微信小程序模板(template)和组件的区别

原文:https://www.cnblogs.com/xiaomm/p/12056597.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!