微信小程序-開發入門(一)


微信小程序已經火了一段時間了,之前一直也在關注,就這半年的發展來看,相對原生APP大部分公司還是不願意將主營業務放到微信平台上,以免受制於騰訊,不過就小程序的應用場景(用完即走和二維碼分發等)還是很值得我們學習的,技術上面如果了解React的話,會發現他們在組件化上面有很多雷同之處。說白了,小程序就是基於微信平台的H5輕應用,微信將系統底層功能(設備、位置、媒體、文件等)和微信自身功能(登錄、支付、分享等)封裝成相應API供小程序調用。

自己根據官方文檔寫過一個DOME,借助和風天氣開放API接口,實現天氣預報.

 

一、小程序基本概念

1、開發工具:為了配合小程序開發,微信專門配備了自己的開發工具,自行選擇對應版本安裝。

 

2、創建項目應用:安裝完成后,打開並掃碼登錄。小程序發布需要企業級的認證公眾號,所以個人訂閱號是不能發布的。所以我這里選擇無AppID,創建項目選擇一個本地空文件夾,勾選創建quick start 項目生成一個demo。

3、編寫小程序:demo初始化並包含了一些簡單的代碼文件,其中app.js、app.json、app.wxss 這三個是必不可少的,小程序會讀取這些文件初始化實例。

  app.js是小程序的初始化腳本,可以在這個文件中監聽小程序的生命周期,申請全局變量和調用API等

  app.json是對小程序的全局配置,pages設置頁面路徑組成(默認第一條為首頁),window設置默認頁面的窗口表現等

  app.wxss 是整個小程序的公共樣式表。類似網站開發中的common.css

 

4、創建頁面:在pages目錄下,由一個文件夾中的四個同名不同類型文件組成。.js是腳本文件,.json是配置文件,.wxss是樣式表文件,.wxml是頁面結構文件,其中json和wxss文件為非必須(默認會繼承app的json和wxss默認設置)。

 

二、小程序的框架

1、小程序的配置

  app.json主要分為五個部分:pages:頁面組,window:框架樣式(狀態欄、導航條、標題、窗口背景色),tabBar:底部菜單,networkTimeout:網絡超時設置,debug:開啟debug模式

  page.json針對頁面單獨設置,層疊掉app.json的全局設置

//app.json
{ "pages":[ "pages/index/index", "pages/logs/logs" ], "window":{ "backgroundTextStyle":"light", "navigationBarBackgroundColor": "#000", "navigationBarTitleText": "WeChat", "navigationBarTextStyle":"white" } }

 

2、小程序的邏輯

  使用App()來注冊一個小程序,必須在app.js中注冊,且不能注冊多個

App({//如下為小程序的生命周期
  onLaunch: function() { },//監聽初始化
  onShow: function() {  },//監聽顯示(進入前台)
  onHide: function() {  },//監聽隱藏(進入后台:按home離開微信)
  onError: function(msg) {  },//監聽錯誤
  //如下為自定義的全局方法和全局變量  
  globalFun:function(){},
  globalData: 'I am global data'
})

  使用Page()注冊一個頁面,在每個頁面的js文件中注冊

Page({
  data: {text: "This is page data."},//頁面數據,用來維護視圖,json格式
  onLoad: function(options) {  },//監聽加載
  onReady: function() {  },//監聽初次渲染完成
  onShow: function() {  },//監聽顯示
  onHide: function() {  },//監聽隱藏
  onUnload: function() {  },//監聽卸載
  onPullDownRefresh: function() {  },//監聽下拉
  onReachBottom: function() {  },//監聽上拉觸底
  onShareAppMessage: function () {  },//監聽右上角分享
  //如下為自定義的事件處理函數(視圖中綁定的)
  viewTap: function() {//setData設置data值,同時將更新視圖
    this.setData({text: 'Set some data for updating view.'})
  }
})

  

3、小程序的視圖與事件綁定

  在每個頁面中的wxml文件中,對頁面js中data進行數據綁定,以及自定義事件綁定

 
<!--{{}}綁定data中的指定數據並渲染到視圖-->
<view class="title">{{text}}</view>

<!--wx:for獲取數組數據進行循環渲染,item為數組的每項-->
<view wx:for="{{array}}"> {{item}} </view>

<!--wx:if條件渲染-->
<view wx:if="{{view == 'WEBVIEW'}}"> WEBVIEW </view>
<view wx:elif="{{view == 'APP'}}"> APP </view>
<view wx:else="{{view == 'MINA'}}"> MINA </view>

<!--模板-->
<template name="staffName">
  <view>FirstName: {{firstName}}, LastName: {{lastName}}</view>
</template>
<template is="staffName" data="{{...template.staffA}}"></template>
<template is="staffName" data="{{...template.staffB}}"></template>

<!--bindtap指定tap事件處理函數為ViewTap-->
<view bindtap="ViewTap"> 點我點我 </view>
 

 

Page({
  data: {//data數據主要用於視圖綁定
    text:"我是一條測試",
    array:[0,1,2,3,4],
    view:"APP",
    template:{
        staffA: {firstName: 'Hulk', lastName: 'Hu'},
        staffB: {firstName: 'Shang', lastName: 'You'}
    }
  },
  ViewTap:function(){console.log('額,點到我了了~')}//自定義事件,主要用於事件綁定
})

 

4、小程序的樣式

  在每個頁面中的wxss文件中,對wxml中的結構進行樣式設置,等同於css,擴展了rpx單位。其中app.wxss默認為全局樣式,作用所有頁面。

 

三、小程序實戰-天氣預報(利用和風天氣API)

先看看完成后的效果,一共三個頁面

1、設置底部菜單和頁面

我們就在quick start生成的demo基礎上進行修改即可,因為涉及圖標icon,我們新建一個images文件夾來存放圖片

在原先pages文件夾中,刪除index和log頁面文件夾,新建weather、city、about三個頁面文件夾,及三個頁面對應的四個文件類型,文件結構如下圖

接下來配置app.json文件

{
"pages": [
"pages/weather/weather",
"pages/about/about",
"pages/city/city"
],
"window": {
"backgroundColor": "#F6F6F6",
"backgroundTextStyle": "dark",
"navigationBarBackgroundColor": "#F6F6F6",
"navigationBarTitleText": "天氣預報",
"navigationBarTextStyle": "black",
"enablePullDownRefresh": true
},
"tabBar": {
"color": "#666",
"selectedColor": "#56abe4",
"backgroundColor": "#ddd",
"borderStyle": "black",
"list": [
{
"pagePath": "pages/weather/weather",
"iconPath": "images/tabbar/weather1.png",
"selectedIconPath": "images/tabbar/weather2.png",
"text": "天氣預報"
},
{
"pagePath": "pages/city/city",
"iconPath": "images/tabbar/city1.png",
"selectedIconPath": "images/tabbar/city2.png",
"text": "設置城市"
},
{
"pagePath": "pages/about/about",
"iconPath": "images/tabbar/about1.png",
"selectedIconPath": "images/tabbar/about2.png",
"text": "關於我"
}
],
"position": "bottom"
}
}

 

2、注冊小程序和整體樣式

修改app.js和app.wxss兩個文件如下

//app.js
App({
//系統事件
onLaunch: function () {//小程序初始化事件
var that = this;
//調用API從本地緩存中獲取數據
that.curid = wx.getStorageSync('curid') || that.curid;//API:獲取本地緩存,若不存在設置為全局屬性
that.setlocal('curid', that.curid);//調用全局方法
},

/*******************************************************/

//自定義全局方法
setlocal: function (id, val) {
wx.setStorageSync(id, val);//API:設置本地緩存
},
//自定義全局屬性
curid: "CN101010100",
version: "1.0"
})
/**app.wxss**/
.container {
display: flex;
flex-direction: column;
align-items: center;
box-sizing: border-box;
}

 

3、頁面的結構(wxml)、樣式(wxss)、邏輯(js)和配置(json)

小程序中的wxml摒棄了HTML標簽, 改用view(類似div)、text(類似span)、icon等等,class同html指定樣式,bindtap綁定事件(類似onclick),該頁面無特殊配置,json文件內容為空(非必須文件)

<!--weather.wxml-->
<view class="container">
<view class="city" bindtap="bindViewTap">
<image class="dwicon" src='../../images/curcity.png'></image>
<text>當前城市:{{basic.location}}</text>
 
<text class="update">最近更新時間:{{loc}}</text>
<image class="zbicon" src='../../images/update.png'></image>
</view>

<view class="weather" bindtap="showcurid">
<image class="section" src="{{icon}}"></image>
<view class="aside">
<text class="temperature">{{now.tmp}}℃</text>
<text>{{now.cond_txt}} | {{now.wind_dir}}{{now.wind_sc}}級</text>
</view>
<view class="other">
<view class="border_r"><text class="title">相對濕度</text><text class="info">{{now.hum}}%</text></view>
<view class="border_r"><text class="title">降水量</text><text class="info">{{now.pcpn}}mm</text></view>
<view><text class="title">能見度</text><text class="info">{{now.vis}}km</text></view>
</view>
</view>

<view class="suggestion">
<text class="title">生活指數</text>
<view class="list">
<view class="list_l">
<image src="../../images/icon/comf.png"></image>
<text>舒適度指數</text>
</view>
<view class="list_r">
<text class="list_t">{{lifestyle[0].brf}}</text>
<text>{{lifestyle[0].txt}}</text>
</view>
</view>
<view class="list">
<view class="list_l">
<image src="../../images/icon/cw.png"></image>
<text>洗車指數</text>
</view>
<view class="list_r">
<text class="list_t">{{lifestyle[6].brf}}</text>
<text>{{lifestyle[6].txt}}</text>
</view>
</view>
<view class="list">
<view class="list_l">
<image src="../../images/icon/drsg.png"></image>
<text>穿衣指數</text>
</view>
<view class="list_r">
<text class="list_t">{{lifestyle[1].brf}}</text>
<text>{{lifestyle[1].txt}}</text>
</view>
</view>
<view class="list">
<view class="list_l">
<image src="../../images/icon/flu.png"></image>
<text>感冒指數</text>
</view>
<view class="list_r">
<text class="list_t">{{lifestyle[2].brf}}</text>
<text>{{lifestyle[2].txt}}</text>
</view>
</view>
<view class="list">
<view class="list_l">
<image src="../../images/icon/sport.png"></image>
<text>運動指數</text>
</view>
<view class="list_r">
<text class="list_t">{{lifestyle[3].brf}}</text>
<text>{{lifestyle[3].txt}}</text>
</view>
</view>
<view class="list">
<view class="list_l">
<image src="../../images/icon/trav.png"></image>
<text>旅游指數</text>
</view>
<view class="list_r">
<text class="list_t">{{lifestyle[4].brf}}</text>
<text>{{lifestyle[4].txt}}</text>
</view>
</view>
<view class="list">
<view class="list_l">
<image src="../../images/icon/uv.png"></image>
<text>紫外線指數</text>
</view>
<view class="list_r">
<text class="list_t">{{lifestyle[5].brf}}</text>
<text>{{lifestyle[5].txt}}</text>
</view>
</view>
 


</view>
</view>
/**weather.wxss**/

/*城市信息*/
.city {padding: 3% 5%; background: #ddd; overflow: hidden;}
.city .dwicon{ width: 30rpx; height: 30rpx; float: left; margin: 5px;}
.city text{font-size: 16px; color: #666; float: left;}
.city .zbicon{ width: 30rpx; height: 30rpx; float: right;margin: 8px 5px;}
.city .update{ font-size: 12px; float: right; width: 110px;}

/*天氣預報*/
.weather{overflow: hidden;background: #cef;color: #58b; padding: 5%; }
.weather .section{ float: left; width: 100px; height: 100px; display: block; }
.weather .aside{ float: right; width:40%; margin-top: 5%; font-size: 12px; }
.weather .aside .temperature{ font-size: 36px; display: block;}
.weather .other{ clear:both; padding-top: 5%; display: flex; }
.weather .other view{ flex:1; text-align: center; }
.weather .other .border_r{ border-right: solid 1px #bbd; }
.weather .other .title{font-size: 12px; color: #bbd; }
.weather .other .info{ display: block; padding-top: 5%; }

/*生活指數*/
.suggestion{ margin-top: 5%;}
.suggestion .title{ display: block; padding: 3% 5%; background: #58b; color: #fff;}
.suggestion .list{ display: flex; font-size: 12px; margin-top: 1px; }
.suggestion .list_l{ flex: 1; text-align: center; background: #cef; color: #bbd; padding: 8px;}
.suggestion .list_l image{ width:30px; height: 30px; display: block; margin: 0 auto;}
.suggestion .list_r{ flex: 4; background: #eee; padding: 8px; color: #aaa;}
.suggestion .list_t{ font-size: 14px; display: block; margin-bottom: 5px; color: #333;}
//weather.js
var app = getApp(); //獲取當前小程序實例,方便使用全局方法和屬性
Page({
//1、頁面數據部分
data: {
cur_id: app.curid,
basic: "",
now: "",
icon: "",
loc:"",
lifestyle: []
}, //設置頁面數據,后面空值將在頁面顯示時通過請求服務器獲取
//2、系統事件部分
onLoad: function() {
var that = this;
wx.showToast({
title: '加載中',
icon: 'loading',
duration: 10000
}) //設置加載模態框
that.getnow(function(d) { //獲取到數據的回調函數
wx.hideToast();
console.info(d)
var icon1 = "https://cdn.heweather.com/cond_icon/" + d.now.cond_code + ".png";
console.info(icon1)
that.setData({
basic: d.basic,
now: d.now,
icon: icon1,
loc:d.update.loc
}) //更新數據,視圖將同步更新
})
that.getsuggestion(function(d) {
console.info(d)
that.setData({
lifestyle: d.lifestyle
}) //更新數據
})
},
//3、自定義頁面方法:獲取當前天氣API
getnow: function(fn) {
wx.request({ //請求服務器,類似ajax
url: 'https://free-api.heweather.net/s6/weather/now',
data: {
location: app.curid,
key: 'e1c701806a6746b6bdf3dd7f7f157ed4'
}, //和風天氣提供用戶key,可自行注冊獲得
header: {
'Content-Type': 'application/json'
},
success: function(res) {
fn(res.data.HeWeather6[0]);
} //成功后將數據傳給回調函數執行
})
},
//獲取生活指數API
getsuggestion: function(fn) {
wx.request({
url: 'https://free-api.heweather.net/s6/weather/lifestyle',
data: {
location: app.curid,
key: 'e1c701806a6746b6bdf3dd7f7f157ed4'
},
header: {
'Content-Type': 'application/json'
},
success: function(res) {
fn(res.data.HeWeather6[0]);
}
})
},
//4、頁面事件綁定部分
bindViewTap: function() {
wx.switchTab({
url: '../city/city'
})
} ,//跳轉菜單頁面
// 下拉刷新
onPullDownRefresh: function () {
// 顯示頂部刷新圖標
wx.showNavigationBarLoading();
var that = this;
wx.showToast({
title: '加載中',
icon: 'loading',
duration: 10000
}) //設置加載模態框
that.getnow(function (d) { //獲取到數據的回調函數
wx.hideToast();
console.info(d)
var icon1 = "https://cdn.heweather.com/cond_icon/" + d.now.cond_code + ".png";
console.info(icon1)
that.setData({
basic: d.basic,
now: d.now,
icon: icon1,
loc: d.update.loc
}) //更新數據,視圖將同步更新
})
that.getsuggestion(function (d) {
console.info(d)
that.setData({
lifestyle: d.lifestyle
}) //更新數據
// 隱藏導航欄加載框
wx.hideNavigationBarLoading();
// 停止下拉動作
wx.stopPullDownRefresh();
})
 
}
})

 

4、注意防坑

跳轉並刷新頁面:需使用onshow來代替onload執行邏輯,onload只在首次打開頁面時執行一次。如:B頁面操作全局數據並跳轉A頁面,A頁面onshow中獲取全局數據更新視圖。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM