怎么在微信小程序中使用template模版

发布时间:2021-05-20 17:12:07 作者:Leah
来源:亿速云 阅读:141

怎么在微信小程序中使用template模版?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

1. 创建 template 模版

不同于 page 和 Component 的创建, 在开发者工具中并不能快速创建一个 template 模版。所以需要单独创建 wxss wxml 文件。

怎么在微信小程序中使用template模版

template.wxml 文件语法

一个 template.wxml 文件中使用 <template> 标签包含一个模版, 一个 template.wxml 文件可以包含多个 <template>模版, 使用 name 属性作为模版的名称。

在模版中可以接受变量, 使用 {{}} 展示。 为变量的传递者由调用该模版的页面传递。

<template name="A">
 <text>template name: {{name}}</text>
</template>
<template name="B">
 <text>template name: {{name}} {{msg}}</text>
</template>

template.wxss 模版样式文件

模版可以拥有自己的样式文件

text{
 color: #cccccc;
}

2. 引用 template 模版

index.wxml

<import src="../tpls/template.wxml" />

<view>
 <template is="A" data="{{name}}"/>
 <template is="B" data="{{name, msg}}"/>
<view>

3. 引用模版样式

在 调用页面的 wxml 中引用了 template.wxml 后,模版的样式并不会引用, 需要在调用页面的 wxss 中单独引用 template.wxss 文件。

index.wxss

@import "./tpls/template.wxss"

4. 模版文件中的事件处理

在模版中定义的事件, 需要调用页面中执行。

template.wxml

<template name="A">
 <text bindtap="handleTap">template name: {{name}}</text>
</template>

index.js

Page({
 data: {},
 handleTap() {
 console.log('template 模版 click')
 }
})

5.  import 有作用域

import 有作用域的概念,即只会 import 目标文件中定义的 template,而不会 import 目标文件中 import 的 template,简言之就是 import 不具有递归的特性。

例如:C 引用 B,B 引用A,在C中可以使用B定义的 template,在B中可以使用A定义的 template ,但是C不能使用A定义的template

6. include 配合 template 模版

如同使用 <import src="xx/xx/xx.wxml"> <tempalte is="A" /> 引用和使用模版一样, 同样也可以使用 <include src="xx/xx/xx.wxml />" 来引用一个模版。

需要注意的是:

<!-- index.wxml -->
<include src="header.wxml"/>

<view> body </view>

<include src="footer.wxml"/>
<!-- header.wxml -->
<view> header </view>
<!-- footer.wxml -->
<view> footer </view>

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

推荐阅读:
  1. 如何在微信小程序中使用template模板
  2. 微信小程序模板template怎么用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

微信小程序 template

上一篇:如何在es6中使用filter() 过滤数组

下一篇:如何在Django中处理多用户类型

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》