小程序 template 模版使用方法

小程序开发语言虽然只能运行在微信小程序中, 可是它的设计一样遵循了主流前端框架的主要特征——组件化,在小程序中组件化的实现有两种方式: template 模版Component 组件。 这两种方式分别适用于不一样的场景。前端

  1. template 模版 主要用于展现,模版中不涉及事件处理, 须要处理的事件逻辑放在调用模版的页面中。 一个 template 模版 只包含 wxml wxss 文件。
  2. Component 组件 做为一个单独的功能模块,不只能够包含页面展现还能够包含该模块的事件逻辑处理。 像一个页面同样, Component 组件 能够包含 wxml wxss js json 文件。

1. 建立 template 模版

不一样于 pageComponent 的建立, 在开发者工具中并不能快速建立一个 template 模版。因此须要单首创建 wxss wxml 文件。json

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 模版样式文件

模版能够拥有本身的样式文件bash

text{
    color: #cccccc;
}
复制代码

2. 引用 template 模版

  1. template 模版的引用须要使用 <import> 标签。 该标签的 src 属性为须要引用模版的路径。
  2. template 模版的使用用 <template> 标签。 使用 is 属性来区别模版文件中定义的模版。
  3. 使用 data 传入模版中的数据。

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.wxmlxss

<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 />" 来引用一个模版。

须要注意的是:

  1. 使用 <include> 引用模版文件时, 并不能分别出模版文件的模版块, 因此使用 <include> 引用的模版文件中只能定义一个模版块。
  2. include 能够将目标文件中除了 <template/> <wxs/> 外的整个代码引入,至关因而拷贝到 include 位置。
<!-- index.wxml -->
<include src="header.wxml"/>

<view> body </view>

<include src="footer.wxml"/>
复制代码
<!-- header.wxml -->
<view> header </view>
复制代码
<!-- footer.wxml -->
<view> footer </view>
复制代码
相关文章
相关标签/搜索