微信小程序模板template总结

没有看过微信小程序template的同学们可以先去官网上了解一下。

以下是对template的几点总结:

一、

template,是一个wxml文件,所以在template中没有处理逻辑的功能(如果希望了解有处理逻辑功能的模块化组件,可以查看下一篇文章)。

二、

在自定义xxx.wxml文件时(xxx是你自定义的wxml文件名),需要用<template>开头,把你的代码定义<template></template>之间。

三、

官网例子显示自定义数据可以通过data传入我们自定义的xxx.wxml(即我们的template里),如果同学们传入的是对象并且希望传入的对象可以展开传入,可以用三个点(...)再加个对象名:

<template is="msgItem" data="{{...item}}"/>
Page({
  data: {
    item: {
      index: 0,
      msg: 'this is a template',
      time: '2016-09-15'
    }
  }
})

但是官网没有说明多个自定义数据是怎么传入的。经过本人的测试,多个数据可以用逗号(,)隔开。

<template is="userhead" data="{{headList,test}}" />

四、

模板拥有自己的作用域,且自定义的template也可以拥有自己的wxss文件,但是需要在引用template的wxml所在的wxss里引用

比如:你有一个index.wxml和一个index.wxss,需要引用一个test_template.wxml,且如果test_template.wxml里需要读取wxss样式文件。

这样就需要index.wxml里添加test_template的template,然后index.wxss引用test_template.wxss。即如下所示:

index.wxml

<view>
    <template is="test_template" data="{{headList}}" />
</view>

index.wxss

@import '../../templates/test/test_template.wxss';

test_template.wxml

<template name="test_template">
  <block wx:for="{{headList}}" wx:key="testItems" wx:for-item="item">
    <view class='title'>
      <!-- 用户头像 -->
      <image src='{{item}}'></image>
    </view>
  </block>
</template>

test_template.wxss

.title {
  margin: 0 auto;
  background: url("http://test.com/wx_image/head_icon.png") no-repeat; 
  -webkit-background-size: 100% auto;
  -moz-background-size: 100% auto;
  -o-background-size: 100% auto;
  background-size: 100% auto;
  background-attachment: scroll;
  position: relative;
  width: 122rpx;
  height: 130rpx;
  border-radius: 50%;
}

.title image {
  width: 120rpx;
  height: 120rpx;
  margin: 10rpx 0 0 0;
  position: absolute;
  border-radius: 50%;
}
以上是本人的一点小总结,如有不足之处,还请各位指正!

猜你喜欢

转载自blog.csdn.net/u013654125/article/details/80729473
今日推荐