小程序中template传值

  小程序中使用template可以减少重复代码块的复用,定义一个template然后在需要的页面导入wxml和wxss文件就可以使用。需要传template中的data时,需要在引用的页面给template数据命名,然后以对象的方式传值。


template的wxml文件:

<!--template/tabBar.wxml-->

<template name="tabBar">
  <view class="tabBar">

    <view class="menu" style="color: {{index_color}};">
      <image src="{{indexImg}}"></image>
    </view>

    <view class="menu">
      <image src="{{postImg}}"></image>
    </view>

    <view class="menu" style="color: {{home_color}};">
      <image src="{{homeImg}}"></image>
    </view>

  </view>
</template>

wxml文件:

<import src="../../../template/tabBar.wxml" />
<template is="tabBar" data="{{...templateData}}"></template>

js文件接收template中传的值。

 data: {
    templateData:{
      indexImg:"",
      postImg:"",
      homeImg:"",
      index_color:"",
      home_color:""
    }
  },