微信小程式——電子書櫥
前言
在初步了解wx.setStorageSync(KEY,DATA),wx.getStorageSync(KEY)的用法后,然后我嘗試寫下該小程式進一步展開應用,
一、準備作業


二、實驗結果
結果如下(示例):





三、實驗代碼
js部分:
Page({
data:{
path:'',
id:'',
tempFilePath:'',
bookList:[
{
id:'01',
title:'Java編程思想',
poster:'../image/tp1.png',
fileUrl:'http://localhost/books/book01.pdf'
},
{
id:'02',
title:'web前端框架技術',
poster:'../image/tp2.png',
fileUrl:'http://localhost/books/book02.pdf'
},
{
id:'03',
title:'微信小程式開發',
poster:'../image/tp3.png',
fileUrl:'http://localhost/books/book03.pdf'
},
{
id:'04',
title:'Node.js開發',
poster:'../image/tp4.png',
fileUrl:'http://localhost/books/book04.pdf'
}
]//bookList陣列存放資料
},
//封裝函式(showTips,openBook,saveBook),方便呼叫
showTips: function(content) {
wx.showModal({
title: '提醒',
content: content,
showCancel: false
})
},
//打開圖書
openBook: function() {
let path=this.data.path
wx.openDocument({
filePath: path,
fileType:'pdf',
success: function(res) {
console.log('打開圖書成功')
},
fail: function(error) {
console.log(error);
}
})
},
//下載圖書
saveBook: function(path) {
var that=this
wx.downloadFile({
url: path,
success:function(res){
if(res.statusCode===200){
console.log(res)
that.setData({
path:res.tempFilePath
})
}
}
})
},
readBook: function(e) {
var that = this
//獲取當前點擊的圖書id
let id = e.currentTarget.dataset.id
console.log('當前的id值:'+id)
//獲取當前點擊的圖書url地址
let fileUrl = e.currentTarget.dataset.file
console.log('當前的fileUrl值:'+fileUrl)
//查看本地快取
let path = wx.getStorageSync(id)
//未曾下載過
if (path ==''){
that.showTips('該書未下載!點擊開始下載')
//異步存盤
wx.setStorageSync(id,fileUrl)
}
//之前下載過的,直接打開
else {
//打開圖書
wx.navigateTo({
url: '../index1/index1',
})
console.log('當前path的值是:'+path)
that.saveBook(path)
that.openBook()
}
}
})
wxml部分:
<view class="demo-box">
<view class='box' wx:for='{{bookList}}' wx:key='book{{index}}' data-file='{{item.fileUrl}}' data-id='{{item.id}}' bindtap='readBook'>
<image src="{{item.poster}}"></image>
<text>{{item.title}}</text>
</view>
</view>
總結
Tips:用戶在書籍未下載之前,點擊書籍,彈出下載提示;初始控制臺和Storage也沒有存盤相應資料,再次點擊會進入下載頁面,這時就會通過wx.setStorageSync() 會在Storage存盤資料;手動回傳上一頁面后,再次雙擊,可以看到控制臺path已經通過getStorageSync得到檔案路徑值了,相應的也可以打開網頁查看里面內容!(代碼功能可能并不是很完善,讀者可以將其看做發布者的一個小程式案例測驗,感謝閱讀!)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/277746.html
標籤:其他
上一篇:【菠蘿狗四足機器人】二次開發教程--第二章 【燒錄Py-apple Dynamics到控制器中】
下一篇:2017藍橋杯C++A組——迷宮
