站長資訊網
        最全最豐富的資訊網站

        匯總微信小程序開發問題

        小程序開發教程欄目介紹微信小程序開發的一些問題

        匯總微信小程序開發問題

        推薦(免費):小程序開發教程

        微信小程序開發問題匯總

        • 樣式如何使用變量
        • video遮罩問題
        • 彈幕自動上推信息流
        • 軟鍵盤問題
        • websocket使用
          • weapp.socket.io
          • 小程序當中的使用

        小程序開發告一段落,總結一下這段時間小程序開發遇到的問題及解決方案,react沖沖沖!!!

        樣式如何使用變量

        在wxss中,定義變量:width:var(–width–);

        在js中,定義變量:viewWidth,并給這個變量賦予想要的值

        在wxml中,使用wxss中的變量和js中的變量:style="–width–: {{ viewWidth }}px"

        video遮罩問題

        在實現直播的功能時,我們需要彈出紅包等遮蓋video的處理,此時會發現,使用z-index屬性在小程序中是無效的,微信開發者文檔提供了cover-view,cover-imge等控件實現遮罩的功能。
        這里值得注意的是cover-view中的background-image屬性是無效的,所以我們要安放背景圖時需要使用到cover-image,并且將它的position設置為absolute, top為0, left也為0即可。

        彈幕自動上推信息流

        匯總微信小程序開發問題
        首先是將這個scroll的高度定死,讓scroll自動滑動到某個item的位置:

            <scroll-view class="danmu-list" scroll-y="true" scroll-into-view="{{'item_' + danmulist.length}}" style="height: {{windowHeight - 890}}rpx">         <view id="{{'item_' + (index + 1)}}" wx:for="{{danmulist}}" class="{{item.nickName == username ? 'danmu-item owner' : 'danmu-item'}}" wx:key="this">           <view class="nickname">{{item.nickName}}:</view>           <view class="content {{ item.system ? 'system' : '' }}" style="color: {{ item.system ? '#71f474' : (item.color || '#fff')}}">{{item.content}}</view>         </view>     </scroll-view>

        為scroll添加樣式:

        .danmu-list {   width: 750rpx;   height: 290rpx;   position: relative;   padding-top: 27rpx;}.danmu-item {   padding: 0 27rpx;}.danmu-item .nickname {   color: #cdd5ff;   font-size: 26rpx;   display: inline-block;}.danmu-item.owner .nickname {   color: #ffab00;}.danmu-item .content {   color: #ffffff;   font-size: 26rpx;   display: inline-block;}

        可以看到在小程序上的實現,明顯比在網頁上要簡單,我們只需要一個scroll-into-view的屬性,并且為每個item添加一個id即可。
        那么有沒有純css的實現呢?當然。
        我們將item都放在一個盒子中,讓盒子的相對于list底部對齊,overflow則進行scroll,這樣同樣能實現現在的效果。

        軟鍵盤問題

        此次開發,需要實現一個輸入框點擊,軟鍵盤彈起,選擇顏色功能。我們看下效果圖:
        匯總微信小程序開發問題
        那么考慮幾個問題:
        1、選擇顏色時鍵盤失去焦點會縮起
        微信小程序提供了一個hold-keyboard屬性
        匯總微信小程序開發問題
        我在input 中設定了hold-keyboard="true"
        2、軟鍵盤彈出時會自動把頁面上推,但是我們僅僅想要軟鍵盤把input框上推而不是整個頁面。
        分析一下這個問題,首先是考慮純css解決方案,把頁面設為fixed,然而不起作用;接下來考慮頁面彈起時減去軟鍵盤的高度讓它恢復到原位,這會帶來兩個問題:1)軟鍵盤彈起后才能獲取軟鍵盤高度,這樣一來頁面的下落會產生嚴重的滯后;2)同樣的不起作用
        這個問題最終的解決方案是這樣的:
        首先查看官方文檔,微信小程序提供了一個adjust-position屬性
        匯總微信小程序開發問題
        設定adjust-position=“false",此時的確不會進行頁面的上推了,但是我們需要的input框上推如何實現?
        我們可以在input的方法參數e.detail.height中拿到軟鍵盤的高度,設定input的高度為e.detail.height的高度即可。
        最終代碼:

         <cover-view wx:if="{{inputParam.colorShow}}" class="color-check" style="bottom: {{inputParam.bottom + (windowWidth / 750 * 90)}}px">    <cover-image class="color-background" src="{{assets}}/images/live-index-danmu-send-color-check.png"></cover-image>    <cover-view class="color-list">      <cover-view wx:for="{{colorStatusList}}" wx:key="this" catchtap="checkColor" data-index="{{index}}" class="{{item.checked == 0 ? 'color-icon' : 'color-icon with-border'}}" style="background-color: {{item.color}}"></cover-view>    </cover-view>  </cover-view>    <view class="enterDanmu" style="bottom: {{inputParam.bottom}}px"> 	  <input hold-keyboard="true" catchtap catchfocus="enterMessage" bindconfirm="loseColor" bindinput="getInputValue" placeholder="發個彈幕唄~" 	     placeholder-style="font-size: 26rpx; color: #09091b" style="color:{{fontcolor}};" 	     value="{{inputParam.inpuentertValue}}" focus="{{inputParam.focus}}" adjust-position="{{false}}"></input>      <image catchtap="sendMessageOperation" class="danmu-btn" src="{{assets}}images/live-index-danmu-send.png"></image>  </view>
        checkColor(e) {     let colorStatusList = this.data.colorStatusList;     let index = e.currentTarget.dataset.index;     let foncolor = colorStatusList[index].color;     let inputParam = this.data.inputParam     inputParam.focus = true     if (colorStatusList[index].checked == true) {       colorStatusList[index].checked = false       foncolor = '#09091b'     } else {       for (let colorIndex in colorStatusList) {         colorStatusList[colorIndex].checked = false       }       colorStatusList[index].checked = true     }     this.setData({       colorStatusList: colorStatusList,       fontcolor: foncolor,       inputParam: inputParam    })   },    getInputValue(e) {     let inputParam = this.data.inputParam;     inputParam.inputValue = e.detail.value;     this.setData({       inputParam: inputParam    })   },    enterMessage(e) {     let inputParam = this.data.inputParam;     inputParam.colorShow = true,     inputParam.focus = true,     inputParam.bottom = e.detail.height    this.setData({       inputParam: inputParam,     })   },    loseColor() {     let inputParam = this.data.inputParam;     inputParam.colorShow = false;     inputParam.focus = false;     inputParam.bottom = 0;     this.setData({       inputParam: inputParam,     })   },    sendMessageOperation(e) {     let inputParam = this.data.inputParam;     if (inputParam.inputValue != '') {       this.socket.emit('message', inputParam.inputValue, this.data.fontcolor);       app.api.send_message(this.data.liveId, this.data.fontcolor, inputParam.inputValue);       inputParam.inputValue = '';       inputParam.colorShow = false       inputParam.focus = false       inputParam.bottom = 0       this.setData({         inputParam: inputParam,       })       console.log("sendMessageOperation")     } else {       inputParam.inputValue = '';       inputParam.colorShow = false       inputParam.focus = false       this.setData({         inputParam: inputParam,       })     }    }

        至于說上面的catchtap則很好理解了,當我們要點擊任意處導致失去焦點時,必定要在外層綁定bindtap事件,那么此處就需要使用catchtap阻止事件的冒泡。
        值得一提的是,微信小程序也提供了一個wx.onKeyboardHeightChange(function callback)方法來監聽鍵盤的高度變化,但是親測這個方法并沒有很好用,嘗試了一下就棄之不用了。

        websocket使用

        我們都知道 HTTP 協議有一個缺陷:通信只能由客戶端發起。那么在這種情況下,如果服務器有連續的狀態變化,客戶端要獲知就非常麻煩。我們只能使用"輪詢",最典型的應用場景就是聊天室了。
        輪詢的效率低,非常浪費資源。因此,工程師們一直在思考,有沒有更好的方法。WebSocket 就是這樣發明的。
        那么如何在微信小程序中使用websocket呢?先來看看本次的需求:
        在觀看直播的過程當中,用戶會進行聊天,服務器要將用戶的彈幕信息推送到每個用戶的手機端。

        weapp.socket.io

        weapp.socket.io是基于socket.io的微信程序環境中的客戶端,以及socket.io-client瀏覽器版本的完整功能。
        安裝方式:

        npm i weapp.socket.io

        簡單使用的代碼:

        <template>     <view class="content">        <button type="primary" @click="send">發送消息</button>     </view></template>
        // 引入 weapp.socket.io.js import io from '@/util/weapp.socket.io.js';export default {     data() {         return {};     },     onLoad() {         // 建立一個socket連接         const socket =(this.socket = io('https://socket-io-chat.now.sh/'));          /**          * 客戶端socket.on()監聽的事件:          */          // 連接成功         socket.on('connect', () => {             console.log('連接成功');         });         // 正在連接         socket.on('connecting', d => {             console.log('正在連接', d);         });         // 連接錯誤         socket.on('connect_error', d => {             console.log('連接失敗', d);         });         // 連接超時         socket.on('connect_timeout', d => {             console.log('連接超時', d);         });         // 斷開連接         socket.on('disconnect', reason => {             console.log('斷開連接', reason);         });         // 重新連接         socket.on('reconnect', attemptNumber => {             console.log('成功重連', attemptNumber);         });         // 連接失敗         socket.on('reconnect_failed', () => {             console.log('重連失敗');         });         // 嘗試重新連接         socket.on('reconnect_attempt', () => {             console.log('嘗試重新重連');         });         // 錯誤發生,并且無法被其他事件類型所處理         socket.on('error', err => {             console.log('錯誤發生,并且無法被其他事件類型所處理', err);         });         // 加入聊天室         socket.on('login', d => {             console.log(`您已加入聊天室,當前共有 ${d.numUsers} 人`);         });         // 接受到新消息         socket.on('new message', d => {             console.log('new message',d);          });         // 有人加入聊天室         socket.on('user joined', d => {             console.log(`${d.username} 來了,當前共有 ${d.numUsers} 人`);          });         // 有人離開聊天室         socket.on('user left', d => {             console.log(`${d.username} 離開了,當前共有 ${d.numUsers} 人`);         });     },     methods: {         send(){             // 發送消息             this.socket.emit('new message', '發送消息')          }     }};

        小程序當中的使用

         initWebSocket(live) {     if(this.socket) {       this.socket.disconnect();       this.socket = null;     }     if(live.step != '直播中') {       return this.setData({ liveTipTime: live.start_time });     }     const username = this.data.username;     const timestamp = Math.floor(Date.now()/1000/60/10);     const token = `gz.${timestamp}.${username}`;     const socket = io( `${socketHost}/chat?id=${this.data.liveId}&token=${token}`);     socket.on('connect', () => {       this.setData({ socketError: '' });       console.log('connection created.')     });     socket.on('join', user => {       let { danmulist } = this.data;       danmulist.push({ nickName: user, content: '加入了房間', system: true });       this.setData({ danmulist, onlineUserCount: this.data.onlineUserCount + 1 });     });     socket.on('message', msg => {       let { danmulist } = this.data;       danmulist.push({ nickName: msg.user, content: msg.content, color: msg.color || '#fff' });       this.videoContext.sendDanmu({ text: msg.content, color: msg.color || '#fff' })       this.setData({ danmulist });       console.log(msg)     });     socket.on('alluser', users => {       //console.log('alluser', users);       this.setData({ onlineUserCount: users.length });     });     socket.on('logout', users => {       console.log('alluser', users)       this.setData({ onlineUserCount: this.data.onlineUserCount - 1 });     });     socket.on('getAlluser', ({ type, users }) => {       console.log('getAlluser', type, users);       if(this.data.isAdmin) {         app.api.lottery_start(type, users).then(x=>{           if(!x.length) {             return wx.showModal({ content: '當前已無符合條件的中獎候選名單,請稍后再試' });           }           wx.showToast({ title: '抽獎成功' });           this.setData({ activeTab: 0 });           this.socket.emit('lotteryStart', type);           this.lottery_result_summary();         }).catch(e=>{           wx.showModal({ title: '抽獎失敗: '+e, showCancel: false });         });       }     });     socket.on('setScore', score => {       const liveIndex = this.data.swiperList.findIndex(x=>x.id == this.data.liveId);       if(this.data.swiperList[liveIndex]) {         this.setData({ [`swiperList[${liveIndex}].score`]: score });       }       console.log('setScore', score)     });     socket.on('lotteryStart', type => {       console.log('lotteryStart', type)       if(this.data.lotteryStatus == 1) {         app.api.lottery_result(type).then(lotteryResult=>{           this.setData({ lotteryStatus: 2, lotteryResult, time2: 10 });           this.countdown();         });       }     });     socket.on('setliveStep', step => {       console.log('setliveStep', step)     });     socket.on('error', e => {       console.error('socket error', e);       wx.showToast({ title: '連接彈幕服務失敗', icon: 'none' });       this.setData({ socketError: e + '' });     })     this.socket = socket;     this.setData({ liveTipTime: '' });   },

        想了解

        贊(0)
        分享到: 更多 (0)
        網站地圖   滬ICP備18035694號-2    滬公網安備31011702889846號
        主站蜘蛛池模板: 国产精品久久久久久| 69SEX久久精品国产麻豆| 亚洲AV无码国产精品麻豆天美| 久久精品视频免费| 少妇人妻精品一区二区三区| 国产一区二区三区精品视频| 国产成人精品久久免费动漫| 亚洲国产精品无码AAA片| 久久精品国产72国产精福利| 青青草国产精品久久久久| 国语自产少妇精品视频| 亚洲国产精品综合久久网络| 国产精品视频全国免费观看| 华人亚洲欧美精品国产| 国精品无码一区二区三区左线| 久久久久久噜噜精品免费直播| 国产成人精品一区在线| 日本精品卡一卡2卡3卡四卡| 国产精品久久影院| 99免费精品视频| 国产精品无码专区| 精品亚洲成AV人在线观看| 一本一道久久a久久精品综合| 日韩熟女精品一区二区三区| 国产日韩高清三级精品人成| 国产激情精品一区二区三区 | 黄床大片免费30分钟国产精品| 99精品影院| 99精品国产一区二区| segui久久国产精品| 成人国产精品动漫欧美一区| 911亚洲精品国内自产| 亚洲精品欧美综合在线| 国产精品怡红院永久免费| 99久久这里只有精品| 国产精品久久影院| 久久精品一区二区| 91亚洲精品自在在线观看| 99精品影院| 国产美女精品视频| 久久久久99精品成人片|