美文网首页
微信小程序之template与component

微信小程序之template与component

作者: 一只不愿透露名字的菜鸟 | 来源:发表于2019-08-09 13:30 被阅读0次

微信小程序内测的时候,学习过一段时间,后面就没接触。回想一下,至今快三年,忘的差不多了😅,最近刚好有个小程序的开发任务,相当于一边做一边学习。现就个人了解的一些小程序相关的知识做个简单分享。templatecomponent的区别与使用。

一、简单介绍

其实templatecomponent功能都差不多,都是实现组件化的方式。不同的是template里面可以定义多个不同的布局样式,不涉及到过多的逻辑处理。而component一般就定义一个布局样式,使用时是直接引用component整个内容,可以在里面实现复杂的逻辑处理。所以在使用上面,不涉及到逻辑业务的,建议使用template,如果涉及到复杂的逻辑业务的,建议使用component

二、template模块的使用

1、创建

创建template(创建indextemplate.wxml和 indextemplate.wxss文件)

<!-- indextemplate.wxml -->

<!-- 创建模块 -->
<!-- 一定要给name赋值 -->
<template name="indextpl">
  <view class="content" bindtap="clickme">这是一个模块</view>
</template>

template样式

/* indextemplate.wxss */

.content{
  background-color: red;
}
2、使用

导入模块的样式文件,并在布局中使用

/* index.wxss */

@import "../../templates/indextemplate.wxss";

导入模块的布局文件

<!-- index.wxml -->

<!-- 导入模块 -->
<import src="../../templates/indextemplate.wxml"/>

<!-- 用is来标识你是用哪一个模块 -->
<template is="indextpl"></template>

由于模块并没有js文件,点击方法需在使用该模块的页面中的js里面去定义

// index.js
  
  clickme: function(e) {
    console.log('模块被点击了')
  }

三、component组件的使用

在目录下右键--->新建component,取名indexcomponent,这样就创建好了一个组件

创建
<!-- indexcomponent.wxml -->
<!-- 跟page里面的写法是一样 -->

<view class="content" bindtap="clickcomponent">我是一个组件</view>

/* indexcomponent.wxss */

.content{
  background-color: green;
}

组件的js文件跟page的不大一样

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

  },
  /**
   * 组件的方法列表
   */
  methods: {
    clickcomponent: function () {
      console.log(this.properties.passvalue)
    }
  }
})

使用(组件的使用不需要导入其他文件了,只需在使用页面的json文件中引入组件名跟路径)
// index.json
//引入组件
{
  "usingComponents": {
    "indexcomponent": "../../components/indexcomponent"
  }
}
<!-- index.wxml -->
<!-- 页面中直接使用 -->
<!--向组件传值 ,字段须跟indexcomponent.js中的属性名一致,如下通过passvalue向组件传递一个值 -->

<indexcomponent passvalue="我是组件"></indexcomponent>

附项目文件结构图


image.png

相关文章

网友评论

      本文标题:微信小程序之template与component

      本文链接:https://www.haomeiwen.com/subject/jveqjctx.html