駕校答題小程式實戰全過程【連載】——3.順序練習和模擬考試
一、目標:
這一節做順序練習與模擬考試,都屬於答題詳細頁面功能,如下圖所示:

1.png

2.png
進度條可以根據答題進度,顯示進度。
這一節主要實現了一些邏輯計算
二、實現方式:
邏輯一:記錄學習題目進度
記錄的核心程式碼,在提交儲存的時候呼叫。當然,也可以在練習離開的時候觸發,這裡給了個按鈕,點選儲存即可儲存學習記錄
const AddLearning = ({ num, result, type = 1 }) => { let current = wx.Bmob.User.current() return new Promise((resolve, reject) => { const query = wx.Bmob.Query('learning'); query.set('bSubjects', '1') query.set('bModels', '1') query.set('num', num) query.set('result', result) query.set('type', type) query.set('uid', current.objectId) query.save().then(res => { resolve(res) }).catch(err => { console.error(err) reject(err) }) }); }
邏輯二:記錄題目回答的對錯
上面的變數result記錄,格式請看上一節資料庫格式說明,是題目的對錯。這裡點選一個選擇就記錄一次,我在頁面data裡面增加了一個items變數來儲存。
選擇答案執行以下程式碼,今天先實現單選,我們單選與多選,判斷事件分開來做,這樣便於邏輯管理
// 單選題 handleFruitChange ({ detail = {}, target = {} }) { let questionInfo = this.data.questionInfo // 判斷單選是否正確 if (target.dataset.id) { console.log('ok') questionInfo.isOk = 1 } this.setData({ questionInfo: questionInfo, current: detail.value }); // 單選自動跳到下一題 this.statistical() // 顯示第幾道題 this.setThisData(this.data.index) this.setData({ index: this.data.index + 1, current: '' }); },
邏輯三:答題相關統計
邏輯二講了,記錄對錯,這裡有一些統計需要拿出來計算,先做單選題,點選選擇,判斷是否正確, 如果正確,記錄到結果物件 [{" id ":" XXX ', '0'}, {" id ":" XXX ", "1"}] ,0代表回答錯誤,1正確
例如錯題個數、對題個數,頁面提示,進度條進一步
statistical () { // 統計錯題個數 let questionErr = this.data.questionErr//錯題個數 let questionOk = this.data.questionOk//錯題個數 let questionInfo = this.data.questionInfo let items = this.data.items let arr = { "id": questionInfo.objectId, "o": 0 } let t = 'error', m = '回答錯誤' if (questionInfo.isOk === 1) { // o 0代表失敗,1代表成功 arr.o = 1 questionOk = questionOk + 1 t = 'success' m = '回答正確' } else { // 錯誤數+1 questionErr = questionErr + 1 } items.push(arr) // 提示 $Message({ content: m, type: t, duration: 2 }); //進度條 let totalW = this.data.index / this.data.total totalW = (totalW * 100).toFixed(2); totalW = totalW < 1 ? 1 : totalW this.setData({ items: items, questionErr: questionErr, questionOk: questionOk, totalW: totalW, }); },
邏輯四:上一題下一題的實現
頁面顯示第幾個題目,我們用陣列的下面來記錄,單電機下一題,我們記錄回答對錯,並且陣列下標+1
// 翻頁 handlePageChange ({ detail }) { const type = detail.type; const current = this.data.current if (current == "") { console.log('空') $Toast({ content: '請選擇答案!', type: 'warning' }); return; } this.statistical() if (type === 'next') { this.setThisData(this.data.index) this.setData({ index: this.data.index + 1, current: '' }); } else if (type === 'prev') { this.setData({ index: this.data.index - 1, current: '' }); this.setThisData(this.data.index) } },
邏輯五:引入模式概念
因為答題頁面邏輯非常多,今天寫這麼多也沒寫完一般, 除了學習模式,後面還有模擬考試模式,這裡不單獨使用另外的頁面來開發,統一在一個頁面。 所以,我們在頁面data里加入model變數,代表模式。
/**
* 這裡有個模式, 練習模式,與模擬考試模式
* model 1.練習模式 2.模擬考試考試
* 練習模式查詢出所有資料練習
* 模擬考試 隨機100題 計算打分
*/
三、總結
練習模式裡面的單項選擇邏輯基本已經做好,下一節將實現模擬考試,計算考試成績等等功能