1. 程式人生 > >【微信小程式學習筆記】1:開發一個帶歷史記錄功能的四則計算器

【微信小程式學習筆記】1:開發一個帶歷史記錄功能的四則計算器

端午CSDN學院促銷,買了微信小程式開發實戰跟著學習一下。

混合模式移動應用

微信小程式是一種Hybrid-App(混合模式移動應用),它是介於Native-App和Web-App之間的,更接近前者,但開發成本小很多。

基本結構

  • pages目錄:其內的每個子目錄是這個小程式的一個頁面,至少應包含wxml和js。
  • app.js:全域性的js。
  • app.wxss:WXSS是微信對CSS的封裝,該檔案是全域性的樣式表。
  • app.json:全域性的配置和註冊檔案,如新增的頁面需要在這裡的pages陣列下注冊。pages陣列下的頁面不用寫字尾名,其第一個頁面表示主介面(預設是index)。
  • util目錄:其內用來存放js工具類,需要使用的時候可以用require
    的方式引進其它js檔案中。
  • project.config.json(新):專案配置檔案。

四則計算器程式碼實現

app.json

在這裡指明這個程式用到的兩個頁面。

"pages":[
    "pages/cal/cal",
    "pages/list/list"
  ]

其它部分用預設的就可以,是預設的index頁面和logs頁面,都沒有使用到。

/pages/cal/cal.wxml

<view class="content">
  <view class="screen">
    {{screenData}}
  </view>
  <view
class='btn-group'>
<view class='item orange' bindtap='clickButton' id="
{{id1}}">退格</view> <view class='item orange' bindtap='clickButton' id="{{id2}}">清屏</view> <view class='item orange' bindtap='clickButton' id="{{id3}}">+/-</view> <view class='item orange'
bindtap='clickButton' id="
{{id4}}">+</view> </view> <view class='btn-group'> <view class='item blue' bindtap='clickButton' id="{{id5}}">9</view> <view class='item blue' bindtap='clickButton' id="{{id6}}">8</view> <view class='item blue' bindtap='clickButton' id="{{id7}}">7</view> <view class='item orange' bindtap='clickButton' id="{{id8}}">-</view> </view> <view class='btn-group'> <view class='item blue' bindtap='clickButton' id="{{id9}}">6</view> <view class='item blue' bindtap='clickButton' id="{{id10}}">5</view> <view class='item blue' bindtap='clickButton' id="{{id11}}">4</view> <view class='item orange' bindtap='clickButton' id="{{id12}}">x</view> </view> <view class='btn-group'> <view class='item blue' bindtap='clickButton' id="{{id13}}">3</view> <view class='item blue' bindtap='clickButton' id="{{id14}}">2</view> <view class='item blue' bindtap='clickButton' id="{{id15}}">1</view> <view class='item orange' bindtap='clickButton' id="{{id16}}">÷</view> </view> <view class='btn-group'> <view class='item blue' bindtap='clickButton' id="{{id17}}">0</view> <view class='item blue' bindtap='clickButton' id="{{id18}}">.</view> <view class='item blue' bindtap='history' id="{{id19}}">歷史</view> <view class='item orange' bindtap='clickButton' id="{{id20}}">=</view> </view> </view>

/pages/cal/cal.js

Page({

  /**
   * 頁面的初始資料,這裡的資料頁面可以讀取
   */
  data: {
    id1:"back",
    id2:"clear",
    id3:"negative",
    id4:"+",
    id5:"9",
    id6:"8",
    id7:"7",
    id8:"-",
    id9:"6",
    id10:"5",
    id11:"4",
    id12:"x",
    id13:"3",
    id14:"2",
    id15:"1",
    id16:"÷",
    id17:"0",
    id18:".",
    id19:"history",
    id20:"=",
    screenData:"0",
    // 記錄是否按下了操作符
    lastIsOpt:false,
    // 用於計算結果的陣列
    arr:[],
    // 用於記錄計算曆史
    logs:[]
  },

  /**
   * 生命週期函式--監聽頁面載入
   */
  onLoad: function (options) {

  },

  /**
   * 生命週期函式--監聽頁面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命週期函式--監聽頁面顯示
   */
  onShow: function () {

  },

  /**
   * 生命週期函式--監聽頁面隱藏
   */
  onHide: function () {

  },

  /**
   * 生命週期函式--監聽頁面解除安裝
   */
  onUnload: function () {

  },

  /**
   * 頁面相關事件處理函式--監聽使用者下拉動作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 頁面上拉觸底事件的處理函式
   */
  onReachBottom: function () {

  },

  /**
   * 使用者點選右上角分享
   */
  onShareAppMessage: function () {

  },

  // 點選計算器上的按鈕,引數event攜帶了所點選元素的資訊
  clickButton: function(event){
    console.log(event.target.id);
    // 獲取當前按下的元素的id
    var id=event.target.id;
    // 待計算的新的資料
    var newdata;
    // 更新前螢幕上的資料
    var sd = this.data.screenData;
    // 退格
    if(id===this.data.id1){
      if('0'===sd)
        return ;
      newdata=sd.substring(0,sd.length-1);
      if("-"===newdata || ""===newdata)
        newdata="0";
      // 去除陣列中最後一個元素
      this.data.arr.pop();
    }
    // 清屏
    else if(id===this.data.id2){
      newdata="0";
      // 陣列清空
      this.data.arr.length=0;
    }
    // 正負切換
    else if(id===this.data.id3){
      if("0"===sd)
        return ;
      // 判斷第一個字元來知道當前是不是負
      var fstChar=sd.substring(0,1);
      if('-'===fstChar){
        newdata = sd.substring(1, sd.length);
        // 去掉陣列頭部的負號
        this.data.arr.shift();
      }
      else{
        newdata = "-" + sd;
        // 在陣列頭部增加負號
        this.data.arr.unshift('-');
      }
    }
    // 等號,執行計算
    else if(id===this.data.id20){
      if('0'===sd)
        return ;
      // 檢驗最後一次按下的是不是運算子,不能以運算子結尾
      if(true===this.data.lastIsOpt)
        return ;
      // 存放按下的鍵的陣列
      var arr=this.data.arr;
      // 存放帶操作符,合成運算元的陣列
      var optarr=[];
      // 存放當前獲得的一個數字的字串形式,合成運算元的字首
      var num="";
      // 記錄當前遇到的運算子
      // var nowOpt;
      // 遍歷按下的鍵的陣列
      for (var i in arr){
        // 如果當前遇到的是數字/小數點/正負號
        if(false===isNaN(arr[i]) || arr[i]===this.data.id18 || arr[i]===this.data.id3){
          num+=arr[i];
        }
        // 否則,是運算子
        else{
          // nowOpt=arr[i];
          // 存入合成運算元陣列
          optarr.push(num);
          optarr.push(arr[i]);
          // 清空當前合成的運算元
          num="";
        }
      }
      // 最後一個數字不會遇到運算子,將它也存入陣列中
      optarr.push(num);
      // 從陣列中的頭一個元素開始計算操作結果
      var result=Number(optarr[0])*1.0;
      // 對於陣列中剩下的每個完整數或操作符
      for(var i=1;i<optarr.length;i++){
        // 僅當遇到操作符時,將當前結果和下一個完整數做操作
        if(true===isNaN(optarr[i])){
          // +
          if(optarr[i]===this.data.id4){
            result+=Number(optarr[i+1]);
          }
          // -
          else if (optarr[i] === this.data.id8) {
            result -= Number(optarr[i + 1]);
          }
          // *
          else if (optarr[i] === this.data.id12) {
            result *= Number(optarr[i + 1]);
          }
          // ÷
          else if (optarr[i] === this.data.id16) {
            result /= Number(optarr[i + 1]);
          }
        }
      }
      // 得到結果並清空陣列
      this.data.arr.length=0;
      // 結果存入陣列,因為可能要繼續計算值
      this.data.arr.push(result);
      newdata=result;
      // 將本次計算存入歷史日誌陣列
      var nowlog=sd+"="+result;
      this.data.logs.push(nowlog);
      // 用歷史日誌陣列更新本地快取,指定一個key
      wx.setStorageSync('calcu-logs', this.data.logs);
    }
    // 操作符或者數字
    else{
      // 按下的如果是操作符
      if(id===this.data.id4 || id===this.data.id8 || id===this.data.id12 || id===this.data.id16){
        // 如果剛剛按過了操作符,或者計算器還沒有數字(即0)
        if(true===this.data.lastIsOpt || '0'===sd){
          return ;
        }
        // 不論剛剛怎麼樣,現在已經按過了操作符
        this.data.lastIsOpt=true;
      }
      // 按下的是數字
      else{
        // 現在已經按過了數字,不是操作符
        this.data.lastIsOpt=false;
      }
      // 操作符和數字共用!
      // 不能以0開頭
      if ('0' === sd) {
        newdata = event.target.id;
      } else {
        newdata = sd + event.target.id;
      }
      // 加入計算陣列中
      this.data.arr.push(event.target.id);
    }
    // 這裡this指的是Page,用setData去直接設定螢幕繫結的值
    this.setData({ screenData: newdata});
  },

  // 點選歷史按鈕
  history:function() {
    // 跳轉到歷史介面
    wx.navigateTo({
      url: '../list/list',
    })
  }
})

/pages/cal/cal.wxss

/* pages/cal/cal.wxss */

/* 整個計算器 */
.content{
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-sizing: border box;
  /* 圖片不能從本地資源獲取 */
  /* background-image: url('../assets/image/bg.jpg'); */
  background-color: gray;
  background-repeat: repeat;
  padding-top: 30rpx;
}

/* 計算器螢幕 */
.screen{
  background-color: white;
  border-radius: 3px;
  text-align: right;
  width:720rpx;
  height: 100rpx;
  padding-right: 10rpx;
  margin-bottom: 30rpx;
}


/* 計算器按鈕行 */
.btn-group{
  display: flex;
  flex-direction: row;
}


/* 計算器上的每一個按鈕 */
.item{
  width: 160rpx;
  min-height: 150rpx;
  margin: 10rpx;
  text-shadow: 0 1px 1px rgba(0,0,0,.3);
  border-radius: 5px;
  text-align: center;
  line-height: 150rpx;
}

/* 橘黃色 */
.orange{
  color: #fef4e9;
  border: solid 1px #da7c0c;
  background-color: #f78d1d;
}

/* 藍色 */
.blue{
  color: #d9eef7;
  border: solid 1px #0076a3;
  background-color: #0095cd;
}

/pages/list/list.wxml

<view class='content'>
  <block wx:for="{{logs}}" wx:for-item="log">
    <view class='item'>{{log}}</view>
  </block>
</view>

/pages/list/list.js

Page({

  /**
   * 頁面的初始資料
   */
  data: {
    // 和主頁面對應的,儲存歷史記錄的陣列
    logs:[]
  },

  /**
   * 生命週期函式--監聽頁面載入
   */
  onLoad: function (options) {
    // 在頁面載入時將陣列從快取中取出來
    var alllogs = wx.getStorageSync('calcu-logs');
    // 然後存到本地資料區對應的陣列中
    this.setData({logs:alllogs});
  },

  /**
   * 生命週期函式--監聽頁面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命週期函式--監聽頁面顯示
   */
  onShow: function () {

  },

  /**
   * 生命週期函式--監聽頁面隱藏
   */
  onHide: function () {

  },

  /**
   * 生命週期函式--監聽頁面解除安裝
   */
  onUnload: function () {

  },

  /**
   * 頁面相關事件處理函式--監聽使用者下拉動作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 頁面上拉觸底事件的處理函式
   */
  onReachBottom: function () {

  },

  /**
   * 使用者點選右上角分享
   */
  onShareAppMessage: function () {

  }
})

/pages/list/list.wxss

/* pages/list/list.wxss */

/* 歷史頁面外層 */
.content{
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-sizing: border-box;
  background-repeat: repeat;
  background-color: gray;
}

/* 歷史記錄的每一項 */
.item{
  width: 90%;
  line-height: 100rpx;
  margin-top: 3rpx;
  margin-bottom: 3rpx;
  border-radius: 3px;
  padding-left: 3rpx;
  color: #fef4e9;
  border: 1px solid #da7c0c;
  background-color: #f78d1d;
}

執行結果

輸入算式

這裡寫圖片描述

計算結果

這裡寫圖片描述

檢視歷史

這裡寫圖片描述