小程序 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>
複製代碼
相關文章
相關標籤/搜索