微信小程序组件封装

第一步,在page下面新建一个template文件,如下图

第二部,在template.wxml中编写公用组件即要封装的代码模块

<!--pages/template/template.wxml-->
<template name="mars">
  <view>
    <text>mars{{step}}</text>
  </view>
</template>

第三部,在需要使用封装的组件的wxml文件里引入,此步最关键

<!--pages/index/index.wxml-->
<view class='address' bindtap='onChangeAddress'>
  <template is="mars" data="{{selectRole:'A',step:0}}"></template>
  <input class='choose-address' placeholder='请选取地点' value='{{chooseAddress}}'></input>
</view>
<import src="/pages/template/template.wxml" />

注意:组件的传值我也卸载代码中了,在父组件index.wxml中添加 data="{{selectRole:'A',step:0}}" 在子组件中是可以直接获取到selectRole和step的值的

就是这么简单粗暴的不行

原文地址:https://www.cnblogs.com/ldlx-mars/p/10598655.html