Home > WeChat Applet > Mini Program Development > Summary of WeChat applet development issues

Summary of WeChat applet development issues

coldplay.xixi
Release: 2020-12-04 16:44:17
forward
7911 people have browsed it

## Mini Program Development Tutorial This column introduces some issues in WeChat Mini Program development

Summary of WeChat applet development issues

Recommended (free):

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
The development of mini programs has come to an end. Let’s summarize the problems and problems encountered in mini program development during this period. Solution, react rush! ! !

How to use variables in style

In wxss, define the variable: width: var(–width–);

In js, define the variable: viewWidth, and give this Assign the desired value to the variable

In wxml, use variables in wxss and variables in js: style="–width–: {

{ viewWidth }}px"

Video masking problem

When 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 barrage automatically pushes up the information flow

Summary of WeChat applet development issues 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>
Copy after login
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;}
Copy after login
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.

Soft Keyboard Problem

In this development, it is necessary to realize the function of clicking an input box, popping up the soft keyboard, and selecting a color. Let’s take a look at the rendering:


Summary of WeChat applet development issues 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
Summary of WeChat applet development issues 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
Summary of WeChat applet development issues 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>
Copy after login
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,
      })
    }

  }
Copy after login
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 协议有一个缺陷:通信只能由客户端发起。那么在这种情况下,如果服务器有连续的状态变化,客户端要获知就非常麻烦。我们只能使用"轮询",最典型的应用场景就是聊天室了。
轮询的效率低,非常浪费资源。因此,工程师们一直在思考,有没有更好的方法。WebSocket 就是这样发明的。
那么如何在微信小程序中使用websocket呢?先来看看本次的需求:
在观看直播的过程当中,用户会进行聊天,服务器要将用户的弹幕信息推送到每个用户的手机端。

weapp.socket.io

weapp.socket.io是基于socket.io的微信程序环境中的客户端,以及socket.io-client浏览器版本的完整功能。
安装方式:

npm i weapp.socket.io
Copy after login

简单使用的代码:

<template>
    <view>
       <button>发送消息</button>
    </view></template>
Copy after login
// 引入 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', '发送消息') 
        }
    }};
Copy after login

小程序当中的使用

 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: '' });
  },
Copy after login

想了解更多编程学习,敬请关注php培训栏目!

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!

Related labels:
source:jianshu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template