## Mini Program Development Tutorial This column introduces some issues in WeChat Mini Program development
Mini Program Development Tutorial
Summary of WeChat Mini Program Development Issues- How to use variables in styles
- Video masking problem
- Barrage automatically pushes information flow
- Soft keyboard problem
- Websocket use
- weapp.socket.io
- Usage in mini programs
{ viewWidth }}px"
Video masking problemWhen implementing the live broadcast function, we need to pop up red envelopes and other processes to cover the video. At this time, we will find that using the z-index attribute is invalid in the mini program. WeChat developer documentation provides Cover-view, cover-imge and other controls are used to implement the mask function. It is worth noting here that the background-image attribute in cover-view is invalid, so when we want to place the background image, we need to use cover-image, and set its position to absolute, top to 0, and left to 0. It can be 0.
The first is to set the height of the scroll and let the scroll automatically slide to the position of a certain item:
????<scroll-view> ????????<view> ??????????<view>{{item.nickName}}:</view> ??????????<view>{{item.content}}</view> ????????</view> ????</scroll-view>Add style to 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;}You can see the implementation on the mini program, which is obviously simpler than on the web page. We only need one attribute
scroll-into-view , and just add an id to each item.
So is there any pure css implementation? certainly.
We put all the items in a box, align the box with the bottom of the list, and scroll the overflow, so that the current effect can be achieved.
Then consider a few issues:
1. When selecting a color, the keyboard will shrink when it loses focus
The WeChat applet provides a
hold-keyboard Attributes
I set
hold-keyboard="true" in the input. 2. The soft keyboard will automatically push the page up when it pops up, but We just want the soft keyboard to push the input box up instead of the entire page.
Analyze this problem. First, consider a pure CSS solution, setting the page to fixed, but it does not work. Next, consider subtracting the height of the soft keyboard when the page pops up to restore it to its original position. This will bring There are two problems: 1) The height of the soft keyboard can only be obtained after the soft keyboard bounces up, which will cause serious lag when the page falls; 2) The same does not work
The final solution to this problem is as follows:
First check the official documentation. The WeChat applet provides an
adjust-position attribute
setting
adjust-position="false", this It is true that the page will not be pushed up at this time, but how to push up the input box we need?
We can get the height of the soft keyboard in the input method parameter e.detail.height, and set the height of the input to the height of e.detail.height.
Final code:
?<cover-view> ???<cover-image></cover-image> ???<cover-view> ?????<cover-view></cover-view> ???</cover-view> ?</cover-view> ? ?<view> ??<input> ?????<image></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, ??????}) ????} ??}As for the above catchtap, it is easy to understand. When we want to click anywhere and lose focus, we must bind the bindtap event in the outer layer, so we need to use it here. catchtap prevents events from bubbling up.
It is worth mentioning that the WeChat applet also provides a
wx.onKeyboardHeightChange(function callback) method to monitor the height changes of the keyboard. However, this method did not work well in personal testing. I tried it. Discarded immediately.
websocket使用
我們都知道 HTTP 協(xié)議有一個缺陷:通信只能由客戶端發(fā)起。那么在這種情況下,如果服務(wù)器有連續(xù)的狀態(tài)變化,客戶端要獲知就非常麻煩。我們只能使用"輪詢",最典型的應(yīng)用場景就是聊天室了。
輪詢的效率低,非常浪費(fèi)資源。因此,工程師們一直在思考,有沒有更好的方法。WebSocket 就是這樣發(fā)明的。
那么如何在微信小程序中使用websocket呢?先來看看本次的需求:
在觀看直播的過程當(dāng)中,用戶會進(jìn)行聊天,服務(wù)器要將用戶的彈幕信息推送到每個用戶的手機(jī)端。
weapp.socket.io
weapp.socket.io是基于socket.io的微信程序環(huán)境中的客戶端,以及socket.io-client瀏覽器版本的完整功能。
安裝方式:
npm?i?weapp.socket.io
簡單使用的代碼:
<template> ????<view> ???????<button>發(fā)送消息</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()監(jiān)聽的事件: ?????????*/ ????????//?連接成功 ????????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('嘗試重新重連'); ????????}); ????????//?錯誤發(fā)生,并且無法被其他事件類型所處理 ????????socket.on('error',?err?=>?{ ????????????console.log('錯誤發(fā)生,并且無法被其他事件類型所處理',?err); ????????}); ????????//?加入聊天室 ????????socket.on('login',?d?=>?{ ????????????console.log(`您已加入聊天室,當(dāng)前共有?${d.numUsers}?人`); ????????}); ????????//?接受到新消息 ????????socket.on('new?message',?d?=>?{ ????????????console.log('new?message',d); ????????}); ????????//?有人加入聊天室 ????????socket.on('user?joined',?d?=>?{ ????????????console.log(`${d.username}?來了,當(dāng)前共有?${d.numUsers}?人`); ????????}); ????????//?有人離開聊天室 ????????socket.on('user?left',?d?=>?{ ????????????console.log(`${d.username}?離開了,當(dāng)前共有?${d.numUsers}?人`); ????????}); ????}, ????methods:?{ ????????send(){ ????????????//?發(fā)送消息 ????????????this.socket.emit('new?message',?'發(fā)送消息')? ????????} ????}};
小程序當(dāng)中的使用
?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:?'當(dāng)前已無符合條件的中獎候選名單,請稍后再試'?}); ??????????} ??????????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:?'連接彈幕服務(wù)失敗',?icon:?'none'?}); ??????this.setData({?socketError:?e?+?''?}); ????}) ????this.socket?=?socket; ????this.setData({?liveTipTime:?''?}); ??},
想了解更多編程學(xué)習(xí),敬請關(guān)注php培訓(xùn)欄目!
The above is the detailed content of Summary of WeChat applet development issues. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Xianyu's official WeChat mini program has quietly been launched. In the mini program, you can post private messages to communicate with buyers/sellers, view personal information and orders, search for items, etc. If you are curious about what the Xianyu WeChat mini program is called, take a look now. What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3. If you want to use it, you must activate WeChat payment before you can purchase it;

Implementing picture filter effects in WeChat mini programs With the popularity of social media applications, people are increasingly fond of applying filter effects to photos to enhance the artistic effect and attractiveness of the photos. Picture filter effects can also be implemented in WeChat mini programs, providing users with more interesting and creative photo editing functions. This article will introduce how to implement image filter effects in WeChat mini programs and provide specific code examples. First, we need to use the canvas component in the WeChat applet to load and edit images. The canvas component can be used on the page

To implement the drop-down menu effect in WeChat Mini Programs, specific code examples are required. With the popularity of mobile Internet, WeChat Mini Programs have become an important part of Internet development, and more and more people have begun to pay attention to and use WeChat Mini Programs. The development of WeChat mini programs is simpler and faster than traditional APP development, but it also requires mastering certain development skills. In the development of WeChat mini programs, drop-down menus are a common UI component, achieving a better user experience. This article will introduce in detail how to implement the drop-down menu effect in the WeChat applet and provide practical

The official WeChat mini program of Xianyu has been quietly launched. It provides users with a convenient platform that allows you to easily publish and trade idle items. In the mini program, you can communicate with buyers or sellers via private messages, view personal information and orders, and search for the items you want. So what exactly is Xianyu called in the WeChat mini program? This tutorial guide will introduce it to you in detail. Users who want to know, please follow this article and continue reading! What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3.

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

To implement the picture rotation effect in WeChat Mini Program, specific code examples are required. WeChat Mini Program is a lightweight application that provides users with rich functions and a good user experience. In mini programs, developers can use various components and APIs to achieve various effects. Among them, the picture rotation effect is a common animation effect that can add interest and visual effects to the mini program. To achieve image rotation effects in WeChat mini programs, you need to use the animation API provided by the mini program. The following is a specific code example that shows how to

Use the WeChat applet to achieve the carousel switching effect. The WeChat applet is a lightweight application that is simple and efficient to develop and use. In WeChat mini programs, it is a common requirement to achieve carousel switching effects. This article will introduce how to use the WeChat applet to achieve the carousel switching effect, and give specific code examples. First, add a carousel component to the page file of the WeChat applet. For example, you can use the <swiper> tag to achieve the switching effect of the carousel. In this component, you can pass b

Implementing the sliding delete function in WeChat mini programs requires specific code examples. With the popularity of WeChat mini programs, developers often encounter problems in implementing some common functions during the development process. Among them, the sliding delete function is a common and commonly used functional requirement. This article will introduce in detail how to implement the sliding delete function in the WeChat applet and give specific code examples. 1. Requirements analysis In the WeChat mini program, the implementation of the sliding deletion function involves the following points: List display: To display a list that can be slid and deleted, each list item needs to include
