关于前端:微信小程序的template模版和component组件有什么区别

前言
除了component,微信小程序中还有另外一种组件化的形式template模版这两者执勤啊的区别是,template次要是作为展现,办法则须要写在调用的页面中定义,而component组件则有本人的业务逻辑,能够看做事一个独立的page页面,简略来说,如果只是作为展现,应用template就足够了,如果波及到的业务逻辑及哦啊胡比拟多,那就最好应用component组件了

一. template模板:

  1. 模板创立:倡议独自创立template目录,在template目录中创立治理模板文件。因为模板只有wxml、wxss文件,而且小程序开发工具并不反对疾速创立模板,因而就须要间接创立wxml、wxss文件了,一个template的模板文件和款式文件只须要命名雷同即可。如果模板较多,倡议在template目录下再创立子目录,寄存独自的模板。
  2. 模板文件:
    template.wxml文件中能写多个模板,用name辨别:

      <template name="demo">
     <view class='tempDemo'>
        <text class='name'>FirstName: {{firstName}}, LastName: {{lastName}}</text>
        <text class='fr' bindtap="clickMe" data-name="{{'Hello! I am '+firstName+' '+LastName+'!'}}"> clcikMe </text>
     </view>
      </template>
  3. 款式文件:
    模板领有本人的款式文件(用户自定义)。

     /* templates/demo/index.wxss */
    .tempDemo{
       width:100%;
    }
      view.tempDemo .name{color:darkorange}
  4. 页面援用:

    page.wxml
    
    <!--导入模板-->
    <import src="../../templates/demo/index.wxml" />
    <!--嵌入模板-->
    <view>
     <text>嵌入模板</text>
     <template is="demo" data="{{...staffA}}"></template><!--传入参数,必须是对象-->
     <template is="demo" data="{{...staffB}}"></template><!--传入参数,必须是对象-->
     <template is="demo" data="{{...staffC}}"></template><!--传入参数,必须是对象-->
    </view>
    page.wxss
    
    @import "../../templates/demo/index.wxss" /*引入template款式*/
    
    page.js
    Page({
     /**
      * 页面的初始数据
      */
     data: {
      staffA: { firstName: 'Hulk', lastName: 'Hu' },
      staffB: { firstName: 'Shang', lastName: 'You' },
      staffC: { firstName: 'Gideon', lastName: 'Lin' }
     },
     clickMe(e) {
      wx.showToast({ title: e.currentTarget.dataset.name, icon: "none", duration: 100000 })
     }
     ......
    })

    备注:

    一个模板文件中能够有多个template,每个template均需定义name进行辨别,页面调用的时候也是以name指向对应的template;
    template模板没有配置文件(.json)和业务逻辑文件(.js),所以template模板中的变量援用和业务逻辑事件都须要在援用页面的js文件中进行定义;
    template模板反对独立款式,须要在援用页面的款式文件中进行导入;
    页面利用template模板须要先导入模板 <import src=”../../templates/demo/index.wxml” /> ,而后再嵌入模板<template is=”demo” data=”{{…staffA}}”></template>

二. Component组件:

  1. 组件创立:新建component目录——创立子目录——新建Component;
  1. 组件编写:新建的component组件也由4个文件形成,与page相似,然而js文件和json文件与页面不同。
js代码:

// components/demo/index.js
Component({
 /**
  * 组件的属性列表
  */
 properties: {
  name: {
   type: String,
   value: ''
  }
 },
/**
  * 组件的初始数据
  */
 data: {
  type: "组件"
 },

 /**
  * 组件的办法列表
  */
 methods: {
  click: function () {
   console.log("component!");
  }
 }
})
json配置文件:

{
  "component": true,
  "usingComponents": {}
}
  1. 组件援用:

页面中援用组件须要在json配置文件中进行配置,代码如下:

{
  "navigationBarTitleText": "模板demo",
  "usingComponents": {
   "demo": "../../components/demo/index" 
  }
 }

而后在模板文件中进行应用就能够了,其中name的值为json配置文件中usingComponents的键值:
<demo name="comp" />
<!–应用demo组件,并传入值为“comp”的name属性(参数)–>
这样就能够了。

PS:组件中不会主动援用公共款式,如果须要则需在款式文件中引入:

@import "../../app.wxss";

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理