目錄
小程序前后端交互
自定義組件的使用
語法說明
properties 定義
案例?
微信小程序的事件對象
e.target和e.currentTarget
?微信小程序的事件傳參
傳參方式一: data-key='value'
傳參方式二: id='value'
scroll-view 使用
?scroll-view 中使用flex布局
scroll-into-view
下拉刷新 上拉加載
微信小程序分享功能的實現(xiàn)方法有兩種:
微信音樂播放器
頁面 布局
組件共享PubSubJS
小程序使用 npm 包
背景音頻api使用說明
代碼示例
小程序分包流程
為什么要分包
分包形式
常規(guī)分包
獨立分包
分包預(yù)下載
支付流程詳細(xì)說明
?小程序獲取用戶唯一標(biāo)識(openId)
小程序前后端交互
語法說明
- 每個微信小程序需要事先設(shè)置通訊域名,小程序只可以跟指定的域名進(jìn)行網(wǎng)絡(luò)通信
- 服務(wù)器域名請在 「小程序后臺-開發(fā)-開發(fā)設(shè)置-服務(wù)器域名」 中進(jìn)行配置
- 默認(rèn)超時時間和最大超時時間都是 60s
- 超時時間可以在 app.json 中通過 networktimeout 配置
- 小程序為了安全起見只支持 Https 請求 wx.request 最大并發(fā)限制 10 個
- 開發(fā)中可以在微信開發(fā)工具中不校驗合法域名
export default (url,data={},method='GET')=>{
return new Promise((resolve,reject)=>{
wx.request({
url:'http://localhost:3000'+url,
data,
success:(res)=>{
resolve(res.data)
},
fail:(err)=>{
reject(err)
}
})
})
}
自定義組件的使用
語法說明
新建component組件 不會生路徑
在使用的父頁面 json中?usingComponents注冊組件
父傳值通過屬性 title="排行榜" 子組件 properties 接收
properties 定義
api 框架----》自定義組件
定義段 | 類型 | 是否必填 | 描述 | 最低版本 |
---|---|---|---|---|
type | 是 | 屬性的類型 | ||
optionalTypes | Array | 否 | 屬性的類型(可以指定多個) | 2.6.5 |
value | 否 | 屬性的初始值 | ||
observer | Function | 否 | 屬性值變化時的回調(diào)函數(shù) |
案例?
子組件
<view class="header">
<text class="title">{{title}}</text>
<view>
<text>{{nav}}</text>
<text class="more"> 查看更多</text>
</view>
</view>
// pages/index/commponents/NavHeader/NavHeader.js
Component({
/**
* 組件的屬性列表
*/
properties: {
title:{
type:String,
value:'默認(rèn)值'
},
nav:{
type:String,
value:'默認(rèn)值'
}
},
})
父組件
{
"usingComponents": {
"NavHeader":"../index/commponents/NavHeader/NavHeader"
}
}
<NavHeader title="推薦歌曲" nav='為你精心推薦'></NavHeader>
微信小程序的事件對象
e.target和e.currentTarget
在小程序的事件回調(diào)觸發(fā)時,會接收一個事件對象,事件對象的參數(shù)中包含一個target和currentTarget屬性,接下來說說這二者的區(qū)別。
<view id='tar-father' bindtap='click'>
父組件
<view id='tar-children'>子組件</view>
</view>
event.target 為其子組件,也就是觸發(fā)該事件的源頭組件,?event.target 為父組件,因為觸發(fā)的源頭也就是父組件本身
event.currentTarget 為事件所綁定的組件??event.currentTarget 始終為事件所綁定的組件
總結(jié):target對應(yīng)的是觸發(fā)事件的源頭組件,這個組件有可能是子組件,有可能是父組件,主要是看執(zhí)行動作的區(qū)域。而currentTarget始終對應(yīng)事件所綁定的組件。
?微信小程序的事件傳參
1. 什么是事件委托
? ? 將子元素的事件委托(綁定)給父元素
2. 事件委托的好處(ul 下面的100li需要添加事件,可以直接綁定再父元素上)
? ?1. 減少綁定的次數(shù)
? ?2. 后期新添加的元素也可以享用之前委托的事件
3. 事件委托的原理
? ?1. 冒泡
4. 觸發(fā)事件的是誰
? ?1. 子元素
5. 如何找到觸發(fā)事件的對象
? ?1. event.target
6. currentTarget VS target
? ?1. currentTarget要求綁定事件的元素一定是觸發(fā)事件的元素
? ?2. target綁定事件的元素不一定是觸發(fā)事件的元素
傳參方式一: data-key='value'
ps:key 可以自定義 傳遞多個
<input class="" data-key="phone" placeholder="請輸入用戶名" bindinput="change"> </input>
<input class="" data-key="password" placeholder="請輸入用戶名" bindinput="change" > </input>
#js
change(evet) {
console.log(evet);
let value = evet.detail.value
let type = evet.currentTarget.dataset.key
this.setData({
[type]: value
})
},
傳參方式二: id='value'
唯一值
<input class="" id="phone" placeholder="請輸入用戶名" bindinput="change"> </input>
<input class="" id="password" placeholder="請輸入用戶名" bindinput="change" > </input>
#js
change(evet) {
console.log(evet);
let value = evet.detail.value
let type = evet.currentTarget.id
this.setData({
[type]: value
})
},
scroll-view 使用
tips y軸滾動時要計算滾動高度
?scroll-view 中使用flex布局
?enable-flex
啟用 flexbox 布局。開啟后,當(dāng)前節(jié)點聲明了?display: flex
?就會成為 flex container,并作用于其孩子節(jié)點。
scroll-view 開啟display:flex 設(shè)置?enable-flex?必須設(shè)置大小否則 scroll-view報錯縱向布局高度
<scroll-view class="scroll" enable-flex scroll-x>
<view class="scrollItem" wx:for='{{recommendList}}' wx:key='id'>
<image src="{{item.picUrl}}"></image>
<text>{{item.name}}</text>
</view>
</scroll-view>
.scroll{
display: flex;
height: 300rpx;
}
scroll-into-view
值應(yīng)為某子元素id(id不能以數(shù)字開頭)。設(shè)置哪個方向可滾動,則在哪個方向滾動到該元素
scroll-into-view 是 scroll-view 的一個屬性,主要作用是用于滾動到指定元素的位置,其對應(yīng)值是元素的id,使用方法如下:
<scroll-view
class="navScroll"
scroll-x
enable-flex
scroll-into-view="{{'scroll' + navid}}"
>
<view class="navItem" id="{{'scroll' + item.id}}"wx:for='{{GroupList}}' wx:key='id'>
<view class="navContent {{navid==item.id?'active':''}}" bindtap='navChange' id="{{item.id}}">
{{item.name}}
</view>
</view>
</scroll-view>
data: {
GroupList: [],
navid: '',
VideoList: [],
isTriggered: false //下拉刷新
},
//tags切換
navChange(event) {
// 保存點擊id ,視頻列表賦值為空
this.setData({
navid: event.currentTarget.id,
VideoList: []
})
//開啟加載提示,發(fā)送請求
wx.showLoading({
title: '正在加載',
})
this.getVideoList(event.currentTarget.id)
},
下拉刷新 上拉加載
下拉刷新
refresher-enabled:開啟自動義下拉刷新
定義下拉刷新時觸發(fā)回調(diào) bindrefresherrefresh
refresher-triggered?設(shè)置當(dāng)前下拉刷新狀態(tài),true 表示下拉刷新已經(jīng)被觸發(fā),false 表示下拉刷新未被觸發(fā) 控制刷新狀態(tài)
上拉觸底
bindscrolltolower定義上拉觸底時觸發(fā)回調(diào)
- ????????//為了實現(xiàn)下拉加載數(shù)據(jù)?1.后端分頁?2.前端分頁
- ????????//?1.后端分頁?一般觸發(fā)請求?告訴后端第幾頁?和條目數(shù)
- ????????//?2.前端分頁?直接返回100條?第一次1-9?觸底之后10-19
//下拉刷新
handleRefresher() {
console.log('下拉刷新');
this.getVideoList(this.data.navid)
},
// 上拉觸底
handleToLower() {
console.log('上拉觸底');
let list=this.data.VideoList
list.push(...list)
this.setData({
VideoList:list
})
}
data: {
GroupList: [],
navid: '',
VideoList: [],
isTriggered: false //下拉刷新
},
<scroll-view
class="view-scroll"
scroll-y
refresher-enabled
bindrefresherrefresh="handleRefresher"
bindscrolltolower="handleToLower"
refresher-triggered="{{isTriggered}}"
>
<view class="vieoItem" wx:for='{{VideoList}}' wx:key='index'>
<video src="{{item.data.previewUrl}}"> </video>
</scroll-view>
微信小程序分享功能的實現(xiàn)方法有兩種:
第一種
在page.js中實現(xiàn)onShareAppMessage,便可在小程序右上角選擇分享該頁面
監(jiān)聽用戶點擊頁面內(nèi)轉(zhuǎn)發(fā)按鈕(button?組件?open-type="share"
)或右上角菜單“轉(zhuǎn)發(fā)”按鈕的行為,并自定義轉(zhuǎn)發(fā)內(nèi)容。
參數(shù) | 類型 | 說明 | 最低版本 |
---|---|---|---|
from | String | 轉(zhuǎn)發(fā)事件來源。button :頁面內(nèi)轉(zhuǎn)發(fā)按鈕;menu :右上角轉(zhuǎn)發(fā)菜單 |
1.2.4 |
target | Object | 如果?from ?值是?button ,則?target ?是觸發(fā)這次轉(zhuǎn)發(fā)事件的?button ,否則為?undefined
|
1.2.4 |
webViewUrl | String | 頁面中包含web-view組件時,返回當(dāng)前web-view的url | 1.6.4 |
onShareAppMessage: function () {
return {
title: '彈出分享時顯示的分享標(biāo)題',
desc: '分享頁面的內(nèi)容',
path: '/page/user?id=123' // 路徑,傳遞參數(shù)到指定頁面。
}
}
判讀用戶點擊的是那個
onShareAppMessage: function ({from}) {
console.log(from);
if(from === 'button'){
return {
title: '來自button的轉(zhuǎn)發(fā)',
page: '/pages/video/video',
imageUrl: '/static/images/nvsheng.jpg'
}
}else {
return {
title: '來自menu的轉(zhuǎn)發(fā)',
page: '/pages/video/video',
imageUrl: '/static/images/nvsheng.jpg'
}
}
}
第二種
自定義按鈕實現(xiàn)分享,在page中添加一個帶有open-type='share'的button標(biāo)簽
點擊該按鈕后,即會自動觸發(fā)已經(jīng)在page.js中定義好的onShareAppMessage方法,實現(xiàn)分享功能。
(<button open-type='share'></button>)。
如上例,path屬性指向的是user頁面,并附帶id=123的參數(shù)。我們只需在user.js的onLoad函數(shù)中,通過options查看傳遞過來的參數(shù):
// user.js
Page({
onLoad: function(options) {
console.log(options);
}
})
微信音樂播放器
頁面 布局
<!-- 進(jìn)度條控制區(qū)域 -->
<view class=".progerss">
<text>{{currentTime}}</text>
<!-- 總進(jìn)度 -->
<cview class="bar">
<!-- 實時進(jìn)度 -->
<view class="audio-bar" style="width: {{width + 'rpx'}}">
<!-- 小圓球 -->
<view class="audio-circle" ></view>
</view>
</cview>
<text>{{endTime}}</text>
</view>
<!-- 底部控制播放區(qū)域 -->
<view class="musicControl">
<text class="iconfont icon-iconsMusicyemianbofangmoshiShuffle"></text>
<text class="iconfont icon-shangyishou" id="pre" bindtap='handleSwitch'></text>
<text class="iconfont {{isPlay?'icon-zanting': 'icon-bofang'}} big" bindtap="handleMusicPlay"></text>
<text class="iconfont icon-next" id="next" bindtap='handleSwitch'></text>
<text class="iconfont icon-iconsMusicyemianbofangmoshiPlayList"></text>
</view>
</view>
.musicControl {
position: absolute;
width: 100%;
bottom: 40rpx;
left: 0;
display: flex;
border-top: 1px solid #ffffff;
}
.musicControl text {
width: 20%;
height: 120rpx;
line-height: 120rpx;
text-align: center;
color: #ffffff;
font-size: 50rpx;
}
.musicControl text .big {
font-size: 80rpx;
}
/* 進(jìn)度條 */
.progerss {
width: 640rpx;
height: 80rpx;
line-height: 80rpx;
display: flex;
position: absolute;
bottom: 200rpx;
}
.progerss .bar {
position: relative;
width: 450rpx;
height: 8rpx;
background: rgba(0, 0, 0, .4);
margin: auto;
}
.bar .audio-bar {
position: absolute;
top: 0;
left: 0;
height: 8rpx;
background-color: red;
z-index: 99;
}
.audio-circle {
position: absolute;
right: -18rpx;
top: -6rpx;
width: 18rpx;
height: 18rpx;
border-radius: 50%;
background-color: #fff;
}
組件共享PubSubJS
1.使用第三方庫: pubsub-js
2. 安裝: npm install pubsub-js
3. 使用:
- a) Import PubSub from ‘pubsub-js’
- b) 訂閱消息: PubSub.subscribe(‘eventName’, callback)
- c) 發(fā)布消息: PubSub.publish(‘eventName’, data)
- d) 取消訂閱: PubSub.unsubscribe(‘eventName’)
小程序使用 npm 包
- 初始化 package.json? ? ?npm init
- 勾選允許使用 npm
- 下載 npm 包
- 構(gòu)建 npm?1. 開發(fā)工具 ---> 工具 ---> 構(gòu)建 npm? ?2. 會將 node_modules 中的包打包到 miniprogram_npm 中
背景音頻api使用說明
- BackgroundAudioManager?獲取實例
- BackgroundAudioManager.onPlay(function callback) 監(jiān)聽背景音頻播放事件
- BackgroundAudioManager.onPause(function callback) 監(jiān)聽背景音頻暫停事件
- BackgroundAudioManager.onStop(function callback)?監(jiān)聽背景音頻停止事件
- BackgroundAudioManager.onTimeUpdate(function callback)?監(jiān)聽背景音頻播放進(jìn)度更新事件,只有小程序在前臺時會回調(diào)
- BackgroundAudioManager.onEnded(function callback)?監(jiān)聽背景音頻自然播放結(jié)束事件
- BackgroundAudioManager.stop() 停止音樂
- BackgroundAudioManager.pause() 暫停音樂
string src
音頻的數(shù)據(jù)源(2.2.3?開始支持云文件ID)。默認(rèn)為空字符串,當(dāng)設(shè)置了新的 src 時,會自動開始播放,目前支持的格式有 m4a, aac, mp3, wav。
number startTime
音頻開始播放的位置(單位:s)。
string title
音頻標(biāo)題,用于原生音頻播放器音頻標(biāo)題(必填)。原生音頻播放器中的分享功能,分享出去的卡片標(biāo)題,也將使用該值。
number currentTime
當(dāng)前音頻的播放位置(單位:s),只有在有合法 src 時返回。(只讀)
代碼示例
//獲取全局app應(yīng)用實例
const app = getApp()
import PubSub from 'pubsub-js'
import request from '../../utils/request'
import moment from 'moment'
Page({
data: {
isPlay: false,
song: {},
id: '',
linkUrl: '',
currentTime: '00:00',
endTime: '00:00',
width: 0
},
onLoad: function (options) {
this.setData({
id: options.id
})
this.getMusicInfo(options.id)
//判斷當(dāng)前音樂是否在播放
console.log(app.globalData.musicId, app.globalData.isMUsicPlay + '全局de', options.id + '點擊');
if (app.globalData.isMUsicPlay && app.globalData.musicId == options.id) {
this.setData({
isPlay: true
})
}
//創(chuàng)建音樂播放的實例對象
this.getBackgroundAudioManager = wx.getBackgroundAudioManager()
// 監(jiān)聽用戶點擊操作系統(tǒng)的播放暫停
this.getBackgroundAudioManager.onPlay(() => {
this.changePlayStatus(true)
app.globalData.musicId = options.id
})
this.getBackgroundAudioManager.onPause(() => {
this.changePlayStatus(false)
})
this.getBackgroundAudioManager.onStop(() => {
this.changePlayStatus(false)
})
// 監(jiān)聽音樂實時播放進(jìn)度
this.getBackgroundAudioManager.onTimeUpdate(() => {
// 實時時長
let time = this.getBackgroundAudioManager.currentTime
// 總時長
let totalTime = this.getBackgroundAudioManager.duration
let currentTime = moment(time * 1000).format('mm:ss')
let width = time / totalTime * 450
this.setData({
currentTime,
width
})
})
//監(jiān)聽音樂播放自然結(jié)束
this.getBackgroundAudioManager.onEnded(() => {
//自動換至下一首音樂,并自動播放
PubSub.publish('SwitchType', 'next');
//將進(jìn)度條長度恢復(fù)為0
this.setData({
width: 0,
endTime: '00:00'
})
})
},
//獲取音樂詳情
async getMusicInfo(ids) {
let {
songs
} = await request('/song/detail', {
ids
})
//轉(zhuǎn)換總實長
let endTime = moment(songs[0].dt).format('mm:ss')
this.setData({
song: songs[0],
endTime
})
wx.setNavigationBarTitle({
title: this.data.song.name,
})
},
//修改狀態(tài)功能函數(shù)
changePlayStatus(isPlay) {
this.setData({
isPlay
})
//修改應(yīng)用全局狀態(tài)
app.globalData.isMUsicPlay = isPlay
},
// 點擊開始暫停按鈕
handleMusicPlay() {
let isPlay = !this.data.isPlay
this.setData({
isPlay
})
let {
id,
linkUrl
} = this.data
this.musicControl(isPlay, id, linkUrl)
},
// 播放 暫停 功能回調(diào)
async musicControl(isPlay, id, linkUrl) {
//性能優(yōu)化: 沒有url時再去請求 有的時候就拿全局變量
if (!linkUrl) {
let {
data
} = await request('/song/url', {
id
})
linkUrl = data[0].url
this.setData({
linkUrl
})
}
if (isPlay) { //播放
// 必須給實例添加url 和title
this.getBackgroundAudioManager.src = linkUrl
this.getBackgroundAudioManager.title = this.data.song.name
} else { //暫停
this.getBackgroundAudioManager.pause()
}
},
// 點擊切歌的回調(diào)
handleSwitch(e) {
let type = e.currentTarget.id
//關(guān)閉當(dāng)前音樂
this.getBackgroundAudioManager.stop()
//發(fā)布消息
PubSub.publish('SwitchType', type);
//訂閱消息拿到回傳id
PubSub.subscribe('musiceId', (msg, id) => {
console.log(msg, id);
//獲取音樂信息
this.getMusicInfo(id)
//自動播放
this.musicControl(true, id)
//接收到之后取消訂閱
PubSub.unsubscribe('musiceId');
})
}
})
小程序分包流程
為什么要分包
- 1. 小程序要求壓縮包體積不能大于 2M,否則無法發(fā)布
- 2. 實際開發(fā)中小程序體積如果大于 2M 就需要使用分包機(jī)制進(jìn)行發(fā)布上傳
- 3. 分包后可解決 2M 限制,并且能分包加載內(nèi)容,提高性能
- 4. 分包后單個包的體積不能大于 2M
- 5. 分包后所有包的體積不能大于 16M
分包形式
- 1. 常規(guī)分包
- 2. 獨立分包
- 3. 分包預(yù)下載
常規(guī)分包
1. 開發(fā)者通過在 app.json subpackages 字段聲明項目分包結(jié)構(gòu)
2. 特點:
a) 加載小程序的時候先加載主包,當(dāng)需要訪問分包的頁面時候才加載分包內(nèi)容
b) 分包的頁面可以訪問主包的文件,數(shù)據(jù),圖片等資源
c) 主包:
主包來源: 除了分包以外的內(nèi)容都會被打包到主包中 通常放置啟動頁/tabBar 頁面
"subPackages":[
{
"root": "songPackge",
"pages": [
"pages/recommendSong/recommendSong",
"pages/songDetail/songDetail"
]
}
],
獨立分包
分包預(yù)下載
支付流程詳細(xì)說明
- 1. 用戶在小程序客服端下單(包含用戶及商品信息)
- 2. 小程序客戶端發(fā)送下單支付請求給商家服務(wù)器
- 3. 商家服務(wù)器同微信服務(wù)器對接獲取唯一標(biāo)識 openID
- 4. 商家服務(wù)器根據(jù) openId 生成商戶訂單(包含商戶信息)
- 5. 商家服務(wù)器發(fā)送請求調(diào)用統(tǒng)一下單 API 獲取預(yù)支付訂單信息
- a) 接口地址: https://api.mch.weixin.qq.com/pay/unifiedorder
- 6. 商家對預(yù)支付信息簽名加密后返回給小程序客戶端
-
a) 簽名方式: MD5b) 簽名字段:小程序 ID, 時間戳, 隨機(jī)串,數(shù)據(jù)包,簽名方式c) 參考地址:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=37. 用戶確認(rèn)支付(鑒權(quán)調(diào)起支付)a) API: wx.requestPayment()8. 微信服務(wù)器返回支付結(jié)果給小程序客戶端9. 微信服務(wù)器推送支付結(jié)果給商家服務(wù)器端

?小程序獲取用戶唯一標(biāo)識(openId)
1. wx.login()文章來源:http://www.zghlxwxcb.cn/news/detail-489227.html
- 2. 發(fā)送 code 給服務(wù)器端
- 3. 服務(wù)器端發(fā)送請求攜帶參數(shù)(code, appSecret, appId)給微信服務(wù)器獲取 openId
- a) 接口地址:
- 4. appSecret,appId 在小程序首頁獲取
- 5. 服務(wù)器獲取 openId 后進(jìn)行加密返回給前端

?文章來源地址http://www.zghlxwxcb.cn/news/detail-489227.html
到了這里,關(guān)于微信小程序項目實戰(zhàn) 微信小程序的事件對象的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!