首頁  >  文章  >  微信小程式  >  匯總微信小程式開發問題

匯總微信小程式開發問題

coldplay.xixi
coldplay.xixi轉載
2020-12-04 16:44:177674瀏覽

小程式開發教學專欄介紹微信小程式開發的一些問題

匯總微信小程式開發問題

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

微信小程式開發問題總結

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

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

樣式如何使用變數

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

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

在wxml中,使用wxss中的變數和js中的變數: style="max-width:90%"

# video遮罩問題

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

彈幕自動上推訊息流

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

    
        
          {{item.nickName}}:
          {{item.content}}
        
    

為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的高度即可。
最終程式碼:

 
   
   
     
   
 
 
 
	  
     
 
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

简单使用的代码:

// 引入 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: '' });
  },

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

以上是匯總微信小程式開發問題的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:jianshu.com。如有侵權,請聯絡admin@php.cn刪除