微信小程序中自定义模板

小程序项目

1. 定义模板。
项目根目录下新建文件夹:templates,用于存放模板。
文件夹templates下新建文件夹:temp,temp下新建文件:temp.wxmltemp.wxss
temp.wxml中,通过 <template name=""></template> 定义模板。
2. 新建页面。
小程序根目录下新建文件夹:test,在文件夹test下新建Page:test
3. 目标页面中使用模板。
目标页面的wxml文件通过<import src=""/>引入模板的wxml文件。
目标页面的wxml文件通过 <template is=""></template> 使用模板。
目标页面的wxss文件得通过@import ""引入模板的wxss文件。

代码涉及的主要文件有:

  1. templates/temp/temp.wxml
  2. templates/temp/temp.wxss
  3. pages/test/test.json
  4. pages/test/test.wxml
  5. pages/test/test.wxss
  6. pages/test/test.js

在这里插入图片描述

templates/temp/temp.wxml

<!-- 定义模板 -->
<template name="my-template">
  <view class="user-box">
    <image class="avatar" src="{
     
     {avatarUrl}}"/>
    <view class="username">{
   
   {username}}</view>
  </view>
</template>

templates/temp/temp.wxss

.user-box{
    
    
  text-align: center;
}
.user-box .avatar{
    
    
  width: 300rpx;
  height: 300rpx;
  border-radius: 50%;
}
.user-box .username{
    
    
  font-size: 48rpx;
  font-family:fantasy;
  color: #1761d8;
  height: 80rpx;
  line-height: 80rpx;
}

pages/test/test.json

{
    
    
  "usingComponents": {
    
    },
  "navigationBarBackgroundColor": "#eee",
  "navigationBarTextStyle": "black",
  "navigationBarTitleText": "我的"
}

pages/test/test.wxml

<import src="/templates/temp/temp.wxml"/>

<view class="test-container">
  <template is="my-template" data="{
     
     {...user}}"></template>
</view>

pages/test/test.wxss

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

.test-container{
    
    
  height: 100%;
  background: #eee;
}

pages/test/test.js

Page({
    
    
  data:{
    
    
    user:{
    
    
      username:"Mr Duck",
      avatarUrl:"/static/images/avatar.png"
    }
  }
})

相关链接

小程序中自定义组件
WXML语法参考>模板
WXML语法参考>引用

猜你喜欢

转载自blog.csdn.net/qzw752890913/article/details/126026999