微信小程序中 template 和 component的区别

795 阅读1分钟

template和component的区别:

  • template中无业务逻辑,component中存在业务逻辑
  • template.wxml文件中能写多个模板,用name属性区分开
  • template中没有js文件,方法需要在使用template的页面中定义,传入的data必须是对象。而component用有自己的js文件
  • template中只有wxml和wxss两种文件,而component中有wxml、wxss、js、json四种文件

一、template

文件结构: image.png

一个wxml文件中可以定义多个template模板,用name区分开。template中用到的css放在独立的wxss文件中,使用时,在使用template模板的文件中的wxss文件引入。

模板定义:

<template name="simpleTmp">
  <image class="noRecordImg" src="/image/noRecord.svg"></image>
  <view class="noRecord">暂时没有记录!</view>
</template>

<template name="complexTmp">  
    // 1、这里有个点击事件。2、{{hello}}是使用模板时传入的属性(参数)
  <text bindtap="templateClick">我是一个模板,我的数据(fromPageData)从使用我的页面传入,我的点击事件(templateClick)定义在使用我的页面中,{{fromPageData}}</text>
</template>

在page或者component中使用:

// page.wxml文件
<view class="containerBg"> 
    我是page.....
  <import src="/templates/noRecord/complexTmp.wxml" />
  <view>
    <template is="complexTmp" data="{{...tmpData}}"/>
  </view>
</view>
// page.wxss
@import '/templates/noRecord/complexTmp.wxss';

因为template中没有js文件,所以数据和方法都在使用他的文件定义

//因为template中没有js文件,所以数据和方法都在使用功能他的文件定义
// page.js
Page({
    data: {
        tmpData:{
            fromPageData: "我是从page传入的数据",
        }
    },
    templateClick(){
        console.log("我在page定义,但是在template使用");
    }
});

二、component

文件结构: image.png

component组件中,wxml的写法和Page的写法一样,js中的写法与Page中的写法不一样
// com.wxml
<view>1A = {{a}}</view>
<view>1B = {{b}}</view>
<view>1SUM = {{sum}}</view>
<button bindtap="onTap">click</button>
// com.js
const computedBehavior = require('miniprogram-computed').behavior;
Component({
  behaviors: [computedBehavior],
  data: {
    a: 1,
    b: 1,
    sum: 2,
  },
  watch: {
    'a, b': function(a, b) {
      console.log("5555");
      this.setData({
        sum: a + b
      })
    },
  },
  methods: {
    onTap() {
      this.setData({
        a: this.data.b,
        b: this.data.a + this.data.b,
      })
    }
  }
});

json文件中,"component"字段必须为true

//"component"字段必须为true
// com.json
{
  "component": true,
  "usingComponents": {}
}