前言
小程序開發語言雖然只能運行在微信小程序中, 但是它的設計同樣遵循了主流前端框架的主要特征——組件化,在小程序中組件化的實現有兩種方式: template 模版 和 Component 組件。 這兩種方式分別適用于不同的場景。
template 模版 主要用于展示,模版中不涉及事件處理, 需要處理的事件邏輯放在調用模版的頁面中。 一個 template 模版 只包含 wxml wxss 文件。 Component 組件 作為一個單獨的功能模塊,不僅可以包含頁面展示還可以包含該模塊的事件邏輯處理。 像一個頁面一樣, Component 組件 可以包含 wxml wxss js json 文件。1. 創建 template 模版
不同于 page 和 Component 的創建, 在開發者工具中并不能快速創建一個 template 模版。所以需要單獨創建 wxss wxml 文件。

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 模版
template 模版的引用需要使用 <import> 標簽。 該標簽的 src 屬性為需要引用模版的路徑。 template 模版的使用用 <template> 標簽。 使用 is 屬性來區別模版文件中定義的模版。 使用 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.wxml
<template name="A"> <text bindtap="handleTap">template name: {{name}}</text></template>index.js
Page({ data: {}, handleTap() { console.log('template 模版 click') }})5. import 有作用域
新聞熱點
疑難解答