微信小程序

1.安裝微信開發者工具

window 64:
https://servicewechat.com/wxa...
window 32:
https://servicewechat.com/wxa...
mac:
https://servicewechat.com/wxa...node

2.建立新項目

開發者工具安裝完成後,打開並使用微信掃碼登陸。選擇添加「項目」,填入AppID,若是沒有,選擇無AppleID,命名"myWeChat",並選擇一個本地的文件夾做爲代碼存儲的目錄,點擊「添加項目」,此時開發者工具會提示,是否須要建立一個 quick start 項目。選擇「是」,開發者工具會幫助咱們在開發目錄裏生成一個簡單的 demo。git

3.編寫代碼

點擊開發者工具左側導航的「編輯」,能夠看到這個項目,已經初始化幷包含了一些簡單的代碼文件。最關鍵也是必不可少的,是 app.js、app.json、app.wxss 這三個。其中,.js後綴的是腳本文件,.json後綴的文件是配置文件,.wxss後綴的是樣式表文件。微信小程序會讀取這些文件,並生成小程序實例。
app.js是小程序的腳本代碼。咱們能夠在這個文件中監聽並處理小程序的生命週期函數、聲明全局變量。調用框架提供的豐富的 API,如本例的同步存儲及同步讀取本地數據。json

app.js:canvas

App({
  onLaunch: function () {
    console.log('App Launch');
    //調用API從本地緩存中獲取數據
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
  },
  onShow: function () {
    console.log('App Show')
  },
  onHide: function () {
    console.log('App Hide')
  },
  getUserInfo:function(cb){
    var that = this
    if(this.globalData.userInfo){
      typeof cb == "function" && cb(this.globalData.userInfo)
    }else{
      //調用登陸接口
      wx.login({
        success: function () {
          wx.getUserInfo({
            success: function (res) {
              that.globalData.userInfo = res.userInfo
              typeof cb == "function" && cb(that.globalData.userInfo)
            }
          })
        }
      })
    }
  },
  globalData:{
    userInfo:null,
    currData: 'I am is global data'
  }
})

app.json 是對整個小程序的全局配置。咱們能夠在這個文件中配置小程序是由哪些頁面組成,配置小程序的窗口背景色,配置導航條樣式,配置默認標題。注意該文件不可添加任何註釋。小程序

app.json:微信小程序

{
  "pages":[
    "pages/index/index",
    "pages/logs/logs",
    "pages/newPage/newPage"
  ],
  "window":{
    "backgroundColor": "#49CB5F",
    "backgroundTextStyle":"dark",
    "navigationBarBackgroundColor": "#F8DBF8",
    "navigationBarTitleText": "xhh",
    "navigationBarTextStyle": "black",
    "enablePullDownRefresh": true
  },
  "tabBar": {
    "color": "#B91ABB",
    "selectedColor": "#A349A4",
    "backgroundColor": "#F8DBF8",
    "borderStyle": "white",
    "list": [{
      "pagePath": "pages/index/index",
      "iconPath": "image/icon_component.png",
      "selectedIconPath": "image/icon_component_HL.png",
      "text": "首頁"
    }, {
      "pagePath": "pages/logs/logs",
      "iconPath": "image/icon_API.png",
      "selectedIconPath": "image/icon_API_HL.png",
      "text": "日誌"
    },{
      "pagePath": "pages/newPage/newPage",
      "iconPath": "image/wechat.png",
      "selectedIconPath": "image/wechatHL.png",
      "text": "其餘"
    }]
  },
  "networkTimeout": {
    "request": 10000,
    "downloadFile": 10000,
    "uploadFile": 10000,
    "connectSocket": 10000
  },
  "debug": false
}

app.wxss 是整個小程序的公共樣式表。咱們能夠在頁面組件的 class 屬性上直接使用app.wxss 中聲明的樣式規則。api

app.wxss:數組

.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  /*padding: 200rpx 0;*/
  padding-top: 200rpx;
  box-sizing: border-box;
}

4.建立頁面

index 頁面,logs 頁面和newPage 頁面都在 pages 目錄下。微信小程序中的每個頁面的【路徑+頁面名】都須要寫在 app.json 的 pages 中,且 pages 中的第一個頁面是小程序的首頁。
每個小程序頁面是由同路徑下同名的四個不一樣後綴文件的組成,如:index.js、index.wxml、index.wxss、index.json。.js後綴的文件是腳本文件,.json後綴的文件是配置文件,.wxss後綴的是樣式表文件,.wxml後綴的文件是頁面結構文件。緩存

index 頁面結構以下。微信

index.wxml:

<view class="container">
  <view  bindtap="bindViewTap" class="userinfo">
    <image class="userinfo-avatar" src="{{userInfo.avatarUrl}}" background-size="cover"></image>
    <text class="userinfo-nickname">{{userInfo.nickName}}</text>
  </view>
  <view class="usermotto">
    <text class="user-motto">{{motto}}</text>
  </view>
  <view class="copyright">{{array[0].msg}}</view>
</view>

本例中使用了<view/>、<image/>、<text/>來搭建頁面結構,綁定數據和交互處理函數。
index.js 是頁面的腳本文件,在這個文件中咱們能夠監聽並處理頁面的生命週期函數、獲取小程序實例,聲明並處理數據,響應頁面交互事件等。

index.js:

//獲取應用實例
var app = getApp();
console.log(app.globalData.currData);
Page({
  data: {
    motto: 'Hello xhh',
    userInfo: {},
    array: [{msg: '版權全部,翻版必究'}, {msg: 'msg2'}]
  },
  //事件處理函數
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    console.log('onLoad')
    var that = this
    //調用應用實例的方法獲取全局數據
    app.getUserInfo(function(userInfo){
      //更新數據
      that.setData({
        userInfo:userInfo
      })
    })
  },
  onReady: function () {
      console.log('onReady');
  },
  onShow: function () {
      console.log('onShow');
  },
  onHide: function () {
      console.log('onHide');
  },
  onUnload: function () {
      console.log('onUnload');
  }
})

index.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;
}
.usermotto {
  margin-top: 200px;
}
.copyright {
  text-align:center;
  font-size:0.8rem;
  color: blueviolet;
  margin-top: 120rpx;
}

頁面的樣式表是非必要的。當有頁面樣式表時,頁面的樣式表中的樣式規則會層疊覆蓋 app.wxss 中的樣式規則。若是不指定頁面的樣式表,也能夠在頁面的結構文件中直接使用 app.wxss 中指定的樣式規則。
index.json 是頁面的配置文件:
頁面的配置文件是非必要的。當有頁面的配置文件時,配置項在該頁面會覆蓋 app.json 的 window 中相同的配置項。若是沒有指定的頁面配置文件,則在該頁面直接使用 app.json 中的默認配置。

index.json:

{
    "backgroundColor":"#49CB5F"
}

logs 頁面結構以下。

logs.wxml:

<view class="container log-list">
  <block wx:for="{{logs}}" wx:for-item="log" wx:key="*this">
    <text class="log-item">{{index + 1}}. {{log}}</text>
  </block>
</view>

logs 頁面使用 <block/> 控制標籤來組織代碼,在 <block/> 上使用 wx:for 綁定 logs 數據,並將 logs 數據循環展開節點。

logs.js:

var util = require('../../utils/util.js');
var common = require('../../utils/common.js');

Page({
  data: {
    logs: [],
  },
  onLoad: function () {
    this.setData({
      logs: (wx.getStorageSync('logs') || []).map(function (log) {
        return util.formatTime(new Date(log))
      })
    })
  },
  onShow: function () {
      common.sayHello('xhh')
  },
  onShareAppMessage: function () {
    return {
      title: '自定義分享標題',
      desc: '自定義分享描述',
      path: '/page/user?id=123'
    }
  }
})

logs.wxss:

.log-list {
  display: flex;
  flex-direction: column;
  padding: 40rpx;
}
.log-item {
  margin: 10rpx;
}

logs.json:

{
    "navigationBarTitleText": "查看啓動日誌"
}

newPage 頁面結構以下。

newPage.wxml:

<block wx:for-items="{{arrayList}}">
  <text> {{index}}: </text>
  <text> {{item}} </text>
  <view></view>
</block>

<view wx:if="{{view == 'WEBVIEW'}}"> WEBVIEW </view>
<view wx:elif="{{view == 'APP'}}"> APP </view>
<view wx:else="{{view == 'view'}}"> VIEW </view>

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

<view bindtap="add"> 點我計數:{{count}} </view>

<button bindtap="changeName"> Click me! Change the data below </button>
<view style="margin-top:10rpx">{{obj.text}}</view>

<view class="section">
  <view class="section__title">日期選擇器:</view>
  <picker mode="date" value="{{date}}" start="2015-09-01" end="2018-01-01" bindchange="bindDateChange">
    <view class="picker">
      <label>當前選擇:</label>
      <input class="dateInput" value="{{date}}" />
    </view>
  </picker>
</view>

<view class="group">
  <block wx:for="{{iconSize}}">
    <icon type="success" size="{{item}}" />
  </block>
</view>
<view class="group">
  <block wx:for="{{iconType}}">
    <icon type="{{item}}" size="45" />
  </block>
</view>
<view class="group">
  <block wx:for="{{iconColor}}">
    <icon type="success" size="45" color="{{item}}" />
  </block>
</view>

<swiper indicator-dots="{{indicatorDots}}" autoplay="{{autoplay}}" interval="{{interval}}" duration="{{duration}}" current="{{currentPage}}">
  <block wx:for-items="{{imgUrls}}">
    <swiper-item>
      <image src="{{item}}" class="slide-image" width="355" height="150" />
    </swiper-item>
  </block>
</swiper>
<button bindtap="changeIndicatorDots" class="btnStyle"> indicator-dots </button>
<button bindtap="changeAutoplay" class="btnStyle"> autoplay </button>
<button bindtap="nextPage" class="btnStyle"> next page </button>
<slider bindchange="intervalChange" show-value min="500" max="2000" /> interval
<slider bindchange="durationChange" show-value min="1000" max="10000" /> duration

<audio poster="{{poster}}" name="{{name}}" author="{{author}}" src="{{src}}" id="myAudio" controls loop></audio>
<button type="primary" class="btnStyle" bindtap="audioPlay">播放</button>
<button type="primary" class="btnStyle" bindtap="audioPause">暫停</button>
<button type="primary" class="btnStyle" bindtap="audio14">設置當前播放時間爲14秒</button>
<button type="primary" class="btnStyle" bindtap="audioStart">回到開頭</button>

<button type="primary" class="btnStyle" bindtap="makeCall">撥打電話</button>

<button type="primary" class="btnStyle" bindtap="sendAjax">發送請求</button>

<button type="primary" class="btnStyle" bindtap="checkMap">查看位置</button>

<canvas style="width: 300px; height: 200px;" canvas-id="firstCanvas"></canvas>

newPage.js:

Page({
  onReady: function (e) {
    // 使用 wx.createAudioContext 獲取 audio 上下文 context
    this.audioCtx = wx.createAudioContext('myAudio');

    wx.showToast({
      title: '成功',
      icon: 'success',
      duration: 2000
    })

      // 使用 wx.createContext 獲取繪圖上下文 context
    var context = wx.createContext()

    context.setStrokeStyle("#00ff00")
    context.setLineWidth(5)
    context.rect(0, 0, 200, 200)
    context.stroke()
    context.setStrokeStyle("#ff0000")
    context.setLineWidth(2)
    context.moveTo(160, 100)
    context.arc(100, 100, 60, 0, 2 * Math.PI, true)
    context.moveTo(140, 100)
    context.arc(100, 100, 40, 0, Math.PI, false)
    context.moveTo(85, 80)
    context.arc(80, 80, 5, 0, 2 * Math.PI, true)
    context.moveTo(125, 80)
    context.arc(120, 80, 5, 0, 2 * Math.PI, true)
    context.stroke()

    // 調用 wx.drawCanvas,經過 canvasId 指定在哪張畫布上繪製,經過 actions 指定繪製行爲
    wx.drawCanvas({
      canvasId: 'firstCanvas',
      actions: context.getActions() // 獲取繪圖動做數組
    })

  },
  data: {
    arrayList: ['item1', 'item2', 'item3', 'item4', 'item5'],
    view: 'WEBVIEW',
    staffA: { firstName: 'Hulk', lastName: 'Hu' },
    staffB: { firstName: 'Shang', lastName: 'You' },
    staffC: { firstName: 'Gideon', lastName: 'Lin' },
    count: 1,
    obj: { text: 'data' },
    iconSize: [20, 30, 40, 50, 60, 70],
    iconColor: [
      'red', 'orange', 'yellow', 'green', 'rgb(0,255,255)', 'blue', 'purple'
    ],
    iconType: [
      'success', 'info', 'warn', 'waiting', 'safe_success', 'safe_warn',
      'success_circle', 'success_no_circle', 'waiting_circle', 'circle', 'download',
      'info_circle', 'cancel', 'search', 'clear'
    ],
    imgUrls: [
      'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg',
      'http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg',
      'http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg'
    ],
    indicatorDots: false,
    autoplay: false,
    interval: 5000, // 自動切換時間間隔
    duration: 1000, // 滑動動畫時長
    currentPage: 1,
    poster: 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg?max_age=2592000',
    name: '此時此刻',
    author: '許巍',
    src: 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E06DCBDC9AB7C49FD713D632D313AC4858BACB8DDD29067D3C601481D36E62053BF8DFEAF74C0A5CCFADD6471160CAF3E6A&fromtag=46',

  },
  changeName: function (e) {
    if (this.data.obj.text == "data") {
      this.setData({
        obj: { text: 'changed data' }
      })
    } else {
      this.setData({
        obj: { text: 'data' }
      })
    }
    console.log(this.data.obj.text);
  },
  add: function (e) {
    this.setData({
      count: this.data.count + 1
    })
  },
  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
    console.log(this.data.date);
  },
  changeIndicatorDots: function (e) {
    this.setData({
      indicatorDots: !this.data.indicatorDots
    })
  },
  changeAutoplay: function (e) {
    this.setData({
      autoplay: !this.data.autoplay
    })
  },
  intervalChange: function (e) {
    this.setData({
      interval: e.detail.value
    })
  },
  durationChange: function (e) {
    this.setData({
      duration: e.detail.value
    })
  },
  nextPage: function (e) {
    var temp = this.data.currentPage + 1;
    if (temp >= 3) {
      temp = 0;
    }
    this.setData({
      currentPage: temp
    })
  },
  audioPlay: function () {
    this.audioCtx.play()
  },
  audioPause: function () {
    this.audioCtx.pause()
  },
  audio14: function () {
    this.audioCtx.seek(14)
  },
  audioStart: function () {
    this.audioCtx.seek(0)
  },
  makeCall: function () {
    wx.makePhoneCall({
      phoneNumber: '15151547384'
    })
  },
  sendAjax: function () {
    wx.request({
      url: 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=ACCESS_TOKEN',
      data: {
        "path": "pages/index?query=1",
        "width": 430
      },
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      success: function (res) {
        console.log(res.data);
      },
      fail: function () {

      },
      complete: function () {

      }
    })
  },
  checkMap: function () {
    wx.getLocation({
      type: 'gcj02', //返回能夠用於wx.openLocation的經緯度
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        wx.openLocation({
          latitude: latitude,
          longitude: longitude,
          scale: 28
        })
      }
    })
  }
})

newPage.wxss:

.dateInput {
    display:inline-block;
    vertical-align: -8px;
    border: 1px solid darkslategray;
}
.section .section__title {
    color: blueviolet;
}
.slide-image{
    width: 100%;
    padding: 40rpx 0; 
}
.btnStyle {
    width:400rpx;
    height:100rpx;
    margin-top:40rpx;
    margin-bottom: 10rpx;
}

newPage.json:

{
    "navigationBarTitleText": "newPage"
}

文件目錄結構以下:
圖片描述

5.配置

app.json 配置項列表:
圖片描述

pages:
接受一個數組,每一項都是字符串,來指定小程序由哪些頁面組成。每一項表明對應頁面的【路徑+文件名】信息,數組的第一項表明小程序的初始頁面。小程序中新增/減小頁面,都須要對 pages 數組進行修改。
文件名不須要寫文件後綴,由於框架會自動去尋找路徑.json,.js,.wxml,.wxss的四個文件進行整合。
window:
用於設置小程序的狀態欄、導航條、標題、窗口背景色。
圖片描述

tabBar:
若是咱們的小程序是一個多 tab 應用(客戶端窗口的底部或頂部有 tab 欄能夠切換頁面),那麼咱們能夠經過 tabBar 配置項指定 tab 欄的表現,以及 tab 切換時顯示的對應頁面。
Tip: 經過頁面跳轉(wx.navigateTo)或者頁面重定向(wx.redirectTo)所到達的頁面,即便它是定義在 tabBar 配置中的頁面,也不會顯示底部的 tab 欄。
tabBar 是一個數組,只能配置最少2個、最多5個 tab,tab 按數組的順序排序。
圖片描述

其中 list 接受一個數組,數組中的每一個項都是一個對象,其屬性值以下:
圖片描述
networkTimeout:
能夠設置各類網絡請求的超時時間。
圖片描述

debug:
能夠在開發者工具中開啓 debug 模式,在開發者工具的控制檯面板,調試信息以 info 的形式給出,其信息有Page的註冊,頁面路由,數據更新,事件觸發 。 能夠幫助開發者快速定位一些常見的問題。
page.json:
每個小程序頁面也可使用.json文件來對本頁面的窗口表現進行配置。 頁面的配置比app.json全局配置簡單得多,只是設置 app.json 中的 window 配置項的內容,頁面中配置項會覆蓋 app.json 的 window 中相同的配置項。
頁面的.json只能設置 window 相關的配置項,以決定本頁面的窗口表現,因此無需寫 window 這個鍵。
圖片描述

6.邏輯層

(1) 註冊程序:
App() 函數用來註冊一個小程序。接受一個 object 參數,其指定小程序的生命週期函數等。
object參數說明:
圖片描述

前臺、後臺定義: 當用戶點擊左上角關閉,或者按了設備 Home 鍵離開微信,小程序並無直接銷燬,而是進入了後臺;當再次進入微信或再次打開小程序,又會從後臺進入前臺。
只有當小程序進入後臺必定時間,或者系統資源佔用太高,纔會被真正的銷燬。
getApp()
咱們提供了全局的 getApp() 函數,能夠獲取到小程序實例。
// other.js

var appInstance = getApp()
console.log(appInstance.globalData) // I am global data

注意:
App() 必須在 app.js 中註冊,且不能註冊多個。
不要在定義於 App() 內的函數中調用 getApp() ,使用 this 就能夠拿到 app 實例。
不要在 onLaunch 的時候調用 getCurrentPage(),此時 page 尚未生成。
經過 getApp() 獲取實例以後,不要私自調用生命週期函數。
(2) 註冊頁面:
Page() 函數用來註冊一個頁面。接受一個 object 參數,其指定頁面的初始數據、生命週期函數、事件處理函數等。
object 參數說明:
圖片描述

初始化數據
初始化數據將做爲頁面的第一次渲染。data 將會以 JSON 的形式由邏輯層傳至渲染層,因此其數據必須是能夠轉成 JSON 的格式:字符串,數字,布爾值,對象,數組。
渲染層能夠經過 WXML 對數據進行綁定。
示例代碼:

<view>{{text}}</view>
<view>{{array[0].msg}}</view>

Page({
  data: {
    text: 'init data',
    array: [{msg: '1'}, {msg: '2'}]
  }
})

生命週期函數:

onLoad: 頁面加載
一個頁面只會調用一次。
接收頁面參數能夠獲取wx.navigateTo和wx.redirectTo及<navigator/>中的 query。
onShow: 頁面顯示
每次打開頁面都會調用一次。
onReady: 頁面初次渲染完成
一個頁面只會調用一次,表明頁面已經準備穩當,能夠和視圖層進行交互。
對界面的設置如wx.setNavigationBarTitle請在onReady以後設置。詳見生命週期
onHide: 頁面隱藏
當navigateTo或底部tab切換時調用。
onUnload: 頁面卸載
當redirectTo或navigateBack的時候調用。
頁面相關事件處理函數
onPullDownRefresh: 下拉刷新
監聽用戶下拉刷新事件。
須要在config的window選項中開啓enablePullDownRefresh。
當處理完數據刷新後,wx.stopPullDownRefresh能夠中止當前頁面的下拉刷新。
onShareAppMessage: 用戶分享
只有定義了此事件處理函數,右上角菜單纔會顯示「分享」按鈕
用戶點擊分享按鈕的時候會調用
此事件須要 return 一個 Object,用於自定義分享內容。

自定義分享字段:
圖片描述

示例代碼:

Page({
  onShareAppMessage: function () {
    return {
      title: '自定義分享標題',
      path: '/page/user?id=123'
    }
  }
})

事件處理函數
除了初始化數據和生命週期函數,Page 中還能夠定義一些特殊的函數:事件處理函數。在渲染層能夠在組件中加入事件綁定,當達到觸發事件時,就會執行 Page 中定義的事件處理函數。
示例代碼:

<view bindtap="viewTap"> click me </view>

Page({
  viewTap: function() {
    console.log('view tap')
  }
})

setData() 參數格式:
接受一個對象,以 key,value 的形式表示將 this.data 中的 key 對應的值改變成 value。
其中 key 能夠很是靈活,以數據路徑的形式給出,如 array[2].message,a.b.c.d,而且不須要在 this.data 中預先定義。
示例代碼:

<!--index.wxml-->
<view>{{text}}</view>
<button bindtap="changeText"> Change normal data </button>
<view>{{array[0].text}}</view>
<button bindtap="changeItemInArray"> Change Array data </button>
<view>{{object.text}}</view>
<button bindtap="changeItemInObject"> Change Object data </button>
<view>{{newField.text}}</view>
<button bindtap="addNewField"> Add new data </button>

//index.js
Page({
  data: {
    text: 'init data',
    array: [{text: 'init data'}],
    object: {
      text: 'init data'
    }
  },
  changeText: function() {
    // this.data.text = 'changed data'  // bad, it can not work
    this.setData({
      text: 'changed data'
    })
  },
  changeItemInArray: function() {
    // you can use this way to modify a danamic data path
    this.setData({
      'array[0].text':'changed data'
    })
  },
  changeItemInObject: function(){
    this.setData({
      'object.text': 'changed data'
    });
  },
  addNewField: function() {
    this.setData({
      'newField.text': 'new data'
    })
  }
})

(3) 模塊化:
模塊化
咱們能夠將一些公共的代碼抽離成爲一個單獨的 js 文件,做爲一個模塊。模塊只有經過 module.exports 或者 exports 才能對外暴露接口。

須要注意的是:

exports 是 module.exports 的一個引用,所以在模塊裏邊隨意更改 exports 的指向會形成未知的錯誤。因此咱們更推薦開發者採用 module.exports 來暴露模塊接口,除非你已經清晰知道這二者的關係。
小程序目前不支持直接引入 node_modules , 開發者須要使用到 node_modules 時候建議拷貝出相關的代碼到小程序的目錄中。
// common.js

function sayHello(name) {
  console.log(`Hello ${name} !`)
}
function sayGoodbye(name) {
  console.log(`Goodbye ${name} !`)
}

module.exports.sayHello = sayHello
exports.sayGoodbye = sayGoodbye

​在須要使用這些模塊的文件中,使用 require(path) 將公共代碼引入

var common = require('common.js')
Page({
  helloMINA: function() {
    common.sayHello('MINA')
  },
  goodbyeMINA: function() {
    common.sayGoodbye('MINA')
  }
})

7.視圖層

(1) WXML
WXML(WeiXin Markup Language)是框架設計的一套標籤語言,結合基礎組件、事件系統,能夠構建出頁面的結構。
用如下一些簡單的例子來看看 WXML 具備什麼能力:
數據綁定:

<!--wxml-->
<view> {{message}} </view>
// page.js
Page({
  data: {
    message: 'Hello MINA!'
  }
})

列表渲染

<!--wxml-->
<view wx:for="{{array}}"> {{item}} </view>
// page.js
Page({
  data: {
    array: [1, 2, 3, 4, 5]
  }
})

條件渲染

<!--wxml-->
<view wx:if="{{view == 'WEBVIEW'}}"> WEBVIEW </view>
<view wx:elif="{{view == 'APP'}}"> APP </view>
<view wx:else="{{view == 'MINA'}}"> MINA </view>
// page.js
Page({
  data: {
    view: 'MINA'
  }
})

模板

<!--wxml-->
<template name="staffName">
  <view>
    FirstName: {{firstName}}, LastName: {{lastName}}
  </view>
</template>

<template is="staffName" data="{{...staffA}}"></template>
<template is="staffName" data="{{...staffB}}"></template>
<template is="staffName" data="{{...staffC}}"></template>
// page.js
Page({
  data: {
    staffA: {firstName: 'Hulk', lastName: 'Hu'},
    staffB: {firstName: 'Shang', lastName: 'You'},
    staffC: {firstName: 'Gideon', lastName: 'Lin'}
  }
})

事件

<view bindtap="add"> {{count}} </view>
Page({
  data: {
    count: 1
  },
  add: function(e) {
    this.setData({
      count: this.data.count + 1
    })
  }
})

(2) WXSS
尺寸單位
rpx(responsive pixel): 能夠根據屏幕寬度進行自適應。規定屏幕寬爲750rpx。如在 iPhone6 上,屏幕寬度爲375px,共有750個物理像素,則750rpx = 375px = 750物理像素,1rpx = 0.5px = 1物理像素。
圖片描述

樣式導入
使用@import語句能夠導入外聯樣式表,@import後跟須要導入的外聯樣式表的相對路徑,用;表示語句結束。
示例代碼:

/** common.wxss **/
.small-p {
  padding:5px;
}
/** app.wxss **/
@import "common.wxss";
.middle-p {
  padding:15px;
}

內聯樣式
框架組件上支持使用 style、class 屬性來控制組件的樣式。
style:靜態的樣式統一寫到 class 中。style 接收動態的樣式,在運行時會進行解析,請儘可能避免將靜態的樣式寫進 style 中,以避免影響渲染速度。

<view style="color:{{color}};" />

class:用於指定樣式規則,其屬性值是樣式規則中類選擇器名(樣式類名)的集合,樣式類名不須要帶上.,樣式類名之間用空格分隔。

<view class="normal_view" />

選擇器
目前支持的選擇器有:
圖片描述

全局樣式與局部樣式
定義在 app.wxss 中的樣式爲全局樣式,做用於每個頁面。在 page 的 wxss 文件中定義的樣式爲局部樣式,只做用在對應的頁面,並會覆蓋 app.wxss 中相同的選擇器。

8.組件

(1)視圖容器:

view
scroll-view
swiper

(2)基礎內容:

icon
text
progress

(3)表單組件:

button
checkbox
form
input 
label
picker
picker-view
radio
slider
switch
textarea

(4)導航組件:

navigator

(5)媒體組件:

audio
image
video

(6)地圖:

map

(7)畫布:

canvas

(8)客服會話:

contact-button

9.API

(1)網絡(2)媒體(3)文件(4)數據緩存(5)位置(6)設備(7)界面(8)開放接口

相關文章
相關標籤/搜索