實例一: include方式引用header.wxml文件
文件引用對于代碼的重用非常重要,例如在web開發中我們可以將公用的header部分和footer等部分進行提取,然后在需要的地方進行引用。
微信小程序里面,是包含引用功能的――include、import。這兩個引用文件的標簽,使用基本差不多,這里先說一下include。
微信中的視圖文件引用,引用過來的都是沒有渲染的,基本類似于直接將引用過來的文件復制到引用位置,所以我們需要重新對其渲染。
實例說明
這里將默認創建的用戶頭像信息提取出到header.wxml中,做為頭部引用,分別由index2.wxml和index3.wxml引用,引用方式為include。
實例代碼
在pages中創建common/header.wxml
從index.wxml中將系統默認創建的用戶信息結構復制到header.wxml中。
header.wxml代碼:
<!--pages/common/header.wxml--> <view bindtap="bindViewTap" class="userinfo"> <image class="userinfo-avatar" src="{{userInfo.avatarUrl}}" background-size="cover"></image> <text class="userinfo-nickname">{{userInfo.nickName}}</text> </view>因為兩個頁面都要包含header.wxml,所以樣式文件就不重復寫了,這里直接將樣式拷貝到app.wxss。
app.wxss代碼:
/**app.wxss**/.userinfo { display: flex; flex-direction: column; align-items: center;}.userinfo-avatar { width: 128rpx; height: 128rpx; margin: 20rpx; border-radius: 50%;}.userinfo-nickname { color: #aaa;}創建index/index2和index/index3

index2.wxml內容:
<!--pages/index/index2.wxml--><view class="container"> <include src="../common/header.wxml" /> <view class="myBtn"> <button type="primary" bindtap="goIndex3">進入index3</button> </view> </view>
因為index2.wxml和index3.wxml都需要userInfo數據,所以這邊在index2獲取到數據后,使用本地存儲進行存儲,index3.wxml讀取本地存儲。
index2.js代碼:
// pages/index/index2.jsvar app = getApp()Page({ data: { userInfo: {}, }, goIndex3:function(){ wx.navigateTo({ url: 'index3' }) }, onLoad: function () { console.log('onLoad') var that = this app.getUserInfo(function (userInfo) { that.setData({ userInfo: userInfo }) //本地存儲 wx.setStorageSync('userInfo', userInfo) }) }})index3.wxml代碼:
<!--pages/index/index3.wxml--><view class="container"> <include src="../common/header.wxml" /> <text>pages/index/index3.wxml</text></view>
index3.js代碼:
// pages/index/index3.jsPage({ data:{ userInfo: {}, }, onLoad:function(options){ this.setData({ userInfo: wx.getStorageSync('userInfo') }) },})實例效果

實例二: import方式引用footer.wxml文件
這個實例使用import來引用文件,import比include要強大的多,待會我再對于這兩都進行一下對比。
import引用方式涉及到了微信的模版(template),這里先說一下template。
微信視圖模版(template)
template也是寫在.wxml中,然后使用<template>...</template>標記指定模版信息,模版下定義:
<template name="msgItem"> 視圖代碼...</template>
使用name屬性,作為模板的名字。
使用模版:
<template is="msgItem" data="{{...item}}"/>data為向模版傳入的數據。
實例說明
使用模版的方式創建footer視圖代碼片,然后用import和template進行代碼的調用。
實例代碼
創建footer.wxml
footer.wxml代碼:
index2.wxml代碼:
實例效果
實例三: 小程序退出時清除本地數據
這里涉及到了小程序的生命周期問題,可以類比一下安卓生命周期,小程序的生命周期在app.js中進行定義:
| 屬性 | 類型 | 描述 | 觸發時機 |
|---|---|---|---|
| onLaunch | Function | 生命周期函數 主站蜘蛛池模板: 乳山市| 乌拉特后旗| 绥阳县| 海兴县| 龙岩市| 岚皋县| 错那县| 增城市| 刚察县| 盐山县| 贡山| 兴国县| 什邡市| 舟曲县| 哈巴河县| 海宁市| 社会| 瑞昌市| 商河县| 铜山县| 会理县| 吉木乃县| 会昌县| 凤庆县| 中超| 台北县| 尼木县| 康定县| 苍溪县| 始兴县| 岳阳县| 昭平县| 大渡口区| 类乌齐县| 应城市| 吉林市| 巴东县| 鄱阳县| 抚松县| 壶关县| 祁阳县| |