微信小程序開發完整流程


1. 注冊小程序賬號

1. 打開微信公眾平台,找到注冊入口

2.選擇賬號類型: 小程序

 

3. 填寫注冊信息-激活

4. 獲取AppID,查看位置(小程序后台->開發)

 2. 下載微信小程序開發工具

下載地址

如果想要使用VSCode編寫小程序的代碼,需要安裝“小程序助手”插件

3. 開發流程

1. 目錄結構

 

.wxml - weixin Markup Language;在.wxml中編寫頁面結構

<view></view>用於包含代碼塊

<text></text>包含的文字可以長按選中

2. 判斷是否授權

App({
    // 判斷是否授權
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已經授權,可以直接調用 getUserInfo 獲取頭像昵稱,不會彈框
          wx.getUserInfo({
            success: res => {
              // 可以將 res 發送給后台解碼出 unionId
              this.globalData.userInfo = res.userInfo

              // 由於 getUserInfo 是網絡請求,可能會在 Page.onLoad 之后才返回
              // 所以此處加入 callback 以防止這種情況
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  globalData: {
    userInfo: null
  }
})

3. 獲取用戶授權

1. 通過授權按鈕申請用戶授權

<!--index.wxml-->
<view class="container">
  <view class="userinfo">
    <!--如果已有用戶信息則不可見或者用戶默認授權-->
    <button wx:if="{{!hasUserInfo && canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo">授權</button>
    <!--獲取用戶信息后展示用戶頭像和昵稱-->
    <block wx:else>
      <image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
      <text class="userinfo-nickname">{{userInfo.nickName}}</text>
    </block>
  </view>
</view>

2. 設置數據初始值

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  }
})

3. 獲取授權后給數據賦值

  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }

4. 獲取用戶信息;兼容沒有open-type="getUserInfo"的版本

Page({
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由於 getUserInfo 是網絡請求,可能會在 Page.onLoad 之后才返回
      // 所以此處加入 callback 以防止這種情況
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在沒有 open-type=getUserInfo 版本的兼容處理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
})

4. 小程序語法

1. 條件渲染和block組件

block標簽相當於ReactJS中的空標簽(<></>),不會改變原有的代碼結構。

block標簽常和if/for聯合使用。

示例:

    <button wx:if="{{1!==1}}">1</button>
    <!--else if-->
    <block wx:elif="{{1!==1}}">
      <text>2</text>
    </block>
    <text wx:else>3</text>

2. 事件綁定

  onTapOut(event) {
    console.log('--out--',event.target.id, '---dataset--',event.target.dataset);
    console.log('--out--',event.currentTarget.id, '---dataset--',event.currentTarget.dataset);
  },
  onTapIn(event) {
    console.log('--in--', event.target.id)
    console.log('--in--', event.currentTarget.id)
  },

1. bind+事件名:不阻止事件冒泡

  <view data-out="1" id="out" class="test" bindtap="onTapOut">
    <view data-in="2" id="in" bindtap="onTapIn">Inner View</view>Outer View
  </view>

1) 單擊Inner View

--in--in
--in--in
--out-- in --dataset-- {in: "2"}
--out-- out --dataset-- {out: "1"}

2) 單擊Outer View

--out--out
--out--out

2. catch+事件名:阻止事件冒泡

  <view id="out" class="test" bindtap="onTapOut">
    <view id="in" catchtap="onTapIn">Inner View</view>Outer View
  </view>

1)單擊Inner View

--in--in
--in--in

2)單擊Outer View

--out--out
--out--out

3. 設置tabBar

在app.json中設置tabBar

  "tabBar": {
    "color": "#aaa", // tabBar默認字體顏色
    "selectedColor": "#333", // 字體選中顏色
    "backgroundColor": "#fff", // 背景顏色
    "borderStyle": "black", // 切換邊框顏色;white/black
    "position": "top", // tabBar所處的位置;top/bottom
    "list": [{// 2-5個
      "pagePath": "pages/index/index",
      "text": "首頁"
    }, {
      "pagePath": "pages/logs/logs",
      "text":"日志"
    }]
  },

4. 設置導航樣式

// app.json中設置  
"window": {
    "backgroundTextStyle": "light",
    "navigationBarBackgroundColor": "#fff",
    "navigationBarTitleText": "WeChat",
    "navigationBarTextStyle": "black"
  },
// window下的屬性,可以在具體頁面中覆蓋
// 如:index.json中
{
   "navigationBarTitleText": "首頁"
}

5. 輪播圖

  <swiper id="swiper"><!--樣式只能通過swiper設置-->
    <swiper-item>
      <image src="/images/1.jpg"></image>
    </swiper-item>
    <swiper-item>
      <image src="/images/2.jpg"></image>
    </swiper-item>
  </swiper>

6. 渲染列表

 <!--循環渲染列表時,必須添加key用於提高性能;
       如果列表項是不同的數字或者字符串,可以使用*this
       for-item指定item的變量
--> 
 <block wx:key="*this" wx:for="{{logs}}" wx:for-item="log">
    <text class="log-item">{{index + 1}}. {{log}}</text>
  </block>

7. 頁面跳轉

    // 跳轉后左上角帶有返回按鈕
    wx.navigateTo({
      url: '../logs/logs'
    })
    // 跳轉后左上角是首頁按鈕
    wx.redirectTo({
      url: '../logs/logs',
    })
    // 跳轉到tabBar的頁面
    wx.switchTab({
      url: '../logs/logs',
    })

8. 頁面生命周期

onLoad(options) { // 頁面首次加載觸發(只一次);可以接收頁面跳轉時攜帶的查詢參數
}
onReady() { // 頁面首次加載時觸發(只一次)
}
onShow() {
 //每次顯示該頁面觸發
}
onHide() {
 // 每次隱藏的時候觸發
}
onPullDownRefresh() {
   // 監聽用戶下拉事件
}
onReachBottom() {
  // 監聽上拉觸底事件
}
// 設置該函數后,該頁面存在分享功能
onShareAppMessage() {
  // 設置分享的具體信息
  return {
     title: "分享信息",
     imageUrl: '',
     path: ''
  }
}

4. 高級用法

1. wx.request的promise封裝

import BASE_URL from './config.js';
export default function request(url, data, header, method) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: BASE_URL + url,
      data,
      header,
      method,
      dataType: 'json',
      responseType: 'text',
      success: function(res) {
        console.log(res);
        if (res) {
          resolve(res.data)
          // 還需進行詳細的狀態碼區分
        } 
      },
      fail: function(res) {
        reject(res);
        // 請求接口失敗,一般是網絡異常等;404/500都是success回調返回的狀態碼
      },
      complete: function(res) {
        // 無論成功失敗都會觸發
      },
    })    
  });
}

2. webView組件

<web-view src="{{h5Src}}"></web-view>
Page({
  data: {
    h5Src: ""
  },
  onLoad(options) {
    const { url } = options;
    this.setData({
      h5Src: decodeURIComponent(url)
    })
  }
})

跳轉函數

  toView() {
    let url = "https://v.youku.com/v_show";
    wx.navigateTo({
      url: '/pages/webView/webView?url=' + encodeURIComponent(url),
    })
  },

3. 選擇通信地址

    // 選擇通信地址
    wx.chooseAddress({
      success(res) {
        console.log(res)
      } 
    })

4. 選擇/獲取定位

  onChooseLocation() {
    // 彈出地圖選擇當前所在的位置
    wx.chooseLocation({
      success: function(res) {
      },
    })
  },
  onGetLocation() {
    // 獲取位置坐標信息
    wx.getLocation({
      success: function(res) {
        console.log(res)
        // 在地圖中定位當前位置
        wx.openLocation({
          latitude: res.latitude,
          longitude: res.longitude,
        })
      },
    })
  },

 


免責聲明!

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



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