2
  1. How to request a graphic verification code

     this.loginCodeSrc = `${BASE_API}/code/loginCode?uid=${this.timeStamp}`;
  1. Countdown 60s

     countdown() {
                    let timeL = 60;
                    let that = this;
                    this.codeDisable = true;
                    this.timer = setInterval(() => {
                        timeL--;
                        if (timeL == 0) {
                            clearInterval(that.timer);
                            that.codeDisable = false;
                            that.codeTips = `获取验证码`;
                        } else {
                            that.time = timeL;
                            that.codeTips = `倒计时${timeL}s`;
                        }
                    }, 1000)
                },
  2. Optimized writing of switch-case

     statusTitleAdapter(status) {
                    let statusMap = {
                        '1': '已下单',
                        '2': '已发货',
                        '3': '已揽件',
                        '4': '运输中',
                        '5': '派送中',
                        '6': '已签收',
                        '7': ''
                    };
                    return statusMap[status+''];
                },
  3. How to modify the default style of components in the uview framework

     // /deep/.u-button,u-button 为组件名
    /deep/.u-button {
                display: flex;
                align-self: center;
                background-color: #a65342;
                height: 68rpx;
                margin: 0 55rpx;
                font-size: 30rpx;
                border-radius: 6rpx;
                color: #FFFFFF;
            }
  4. the height of the navigation bar

     margin-top: calc(var(--status-bar-height) + 88rpx);
  5. space  
  6. Prevent event passthrough

     @click.native.stop=""
  7. Back to top

     //返回顶部
                backToTop() {
                    uni.pageScrollTo({
                        scrollTop: 0,
                        duration: 100
                    });
                },
  8. text tag text only shows two lines

     //文本只显示两行
                                    display: -webkit-box;
                                    -webkit-box-orient: vertical;
                                    -webkit-line-clamp: 2;
                                    overflow: hidden;
  1. The mutual influence of uniapp array data modification is caused by shallow copy, which can be solved by copying with deep copy.
  2. Check the amount of code under Git: git log --author="ningjianwen" --since=2022-04-11 --before=2022-06-07 --pretty=tformat: --numstat | awk '{ add += $1 ; subs += $2; loc += $1 + $2 } END { printf "added lines: %s, removed lines: %s, total lines: %s\n", add, subs, loc }' -;
  3. In scss mode, the background color with transparency is set in the following ways to take effect. In less mode, an error is reported when compiling.

     rgba($color: #ffc663, $alpha: 0.4)
  4. Text exceeds display ellipsis

     //超出隐藏
    overflow-x: hidden;
    //溢出显示
    text-overflow: ellipsis;
    //文本一行不换行直到遇到换行符
    white-space: nowrap;
  5. The method of uniapp to return to the previous page:

     goback() {
                    let canNavBack = getCurrentPages();
                    if(canNavBack && canNavBack.length>1) {  
                        uni.navigateBack({  
                          delta: 1  
                        });  
                    } else {  
                        history.back();
                    }
                },
  6. The library moment that formats the date and calculates the countdown, the instance method is as follows:

     //待付款,计算剩余时间
                            if (that.orderDetails.orderStatus == '1') {
                                
                                if(that.orderDetails.expirationTime){
                                    let date = that.orderDetails.expirationTime;
                                    that.orderDetails["remainingTime"] = this.moment(date).diff(new Date().getTime());
                                }else{
                                    that.orderDetails["remainingTime"] = "0";
                                }
                            }
  7. When deleting array data, you cannot delete it while traversing. Although the program will not report an error, the result of deletion is that less data will be deleted. Solution:

    1.) Reverse order traversal and deletion, even if there is data deletion, it does not affect the traversal and deletion of subsequent data.

    2.) During positive-order traversal, in the cycle in which data is deleted, the index needs to be decremented and restored, so as not to cause data omission during data traversal.

    3.) Use filter for data filtering target array.

  8. Whether the fill mode of the image when using image is widthFix or heightFix , it is best to set the maximum width or height of the image to prevent the user from uploading an abnormal image, causing the page The layout is messed up.
  9. Date formatting function (format the received date as "HH:mm, yesterday HH:mm, MM-dd HH:mm, yyyy-MM-dd HH:mm"):

     formatTime(value) {
                    var format = (function() {
                        function fix(str) {
                            str = '' + (String(str) || '');
                            return str.length <= 1 ? '0' + str : str;
                        }
    
                        var maps = {
                            'yyyy': function(date) {
                                return date.getFullYear()
                            },
                            'MM': function(date) {
                                return fix(date.getMonth() + 1);
                            },
                            'dd': function(date) {
                                return fix(date.getDate())
                            },
                            'HH': function(date) {
                                return fix(date.getHours())
                            },
                            'mm': function(date) {
                                return fix(date.getMinutes())
                            },
                            'ss': function(date) {
                                return fix(date.getSeconds())
                            }
                        }
    
                        var trunk = new RegExp(Object.keys(maps).join('|'), 'g');
    
                        return function(value, format) {
    
                            if (!value) {
                                return '--';
                            }
    
                            format = format || 'yyyy-MM-dd HH:mm';
                            value = Number(value);
                            value = new Date(value);
    
                            return format.replace(trunk, function(capture) {
                                return maps[capture] ? maps[capture](value) : '';
                            });
                        }
                    })
                    if (value == '' || value == undefined) return '--';
                    var time = new Date(value),
                        now = new Date(),
                        _time = new Date(value).setHours(0, 0, 0, 0),
                        _now = new Date().setHours(0, 0, 0, 0),
                        duration = 24 * 60 * 60 * 1000;
                    if (_now - _time == 0) {
                        return formatDate(time, 'hh:mm');
                    } else if (_now - _time == duration) {
                        return "昨天 " + this.formatDate(time, 'hh:mm');
                    } else if (Math.abs(_now - _time) >= duration && time.getYear() == now.getYear()) {
                        return formatDate(time, 'MM-dd hh:mm');
                    } else {
                        return formatDate(time, 'yyyy-MM-dd hh:mm');
                    }
                },
  10. The top suction effect after the title in the middle of the page slides up:

     &.scrolltop {
                        // position: absolute;
                        // top: 0;
                        // left: 0;
                        position: -webkit-sticky;
                        /* Safari */
                        position: sticky;
                        top: calc(var(--status-bar-height));
                        left: 0;
                        z-index: 3;
                        width: 100%;
                        z-index: 999;
                        background: #F7F1E8;
                    }
    1. The key attributes of vertical layout of text text:

       word-wrap: break-word;
 21. Uniapp 自带的复制粘贴方法,复制内容时页面跳动的解决方案:
 export function copyText(text) {
    // h5 copy功能
    var textareaC = document.createElement('textarea');
    textareaC.setAttribute('readonly', 'readonly'); //设置只读属性防止手机上弹出软键盘
    textareaC.value = text; //textarea的value
    document.body.appendChild(textareaC); //将textarea添加为body子元素
    textareaC.select();
    
    var res = document.execCommand('copy');
    document.body.removeChild(textareaC);//移除DOM元素
    uni.showToast({
        icon: 'success',
        title: '复制成功!'
    });
    
    return res
}
  1. When converting a string to a date, due to system differences, the iOS system cannot recognize the '-' in the middle of the string, and needs to be replaced to obtain the correct value.

     let receiptTime = this.orderDetails.receiptTime||'';
                        receiptTime = receiptTime.replace(/-/g, "/"); //解决iOS系统不识别 日期中间的 - 的问题
                        //确认收货后30天内,还可以进行售后申请
                        let date1 = new Date(receiptTime).getTime() + 30 * 24 * 60 * 60 * 1000;
                        let date2 = new Date().getTime();
                        if((date2 - date1) < 0) {
                            return true;
                        }
                        return false;
    1. Two components are arranged in the same row, when a component is squeezed. You can set a fixed width for the extruded component, and set the other component flex:1%; to make it occupy the remaining space.
    2. When using the u-list component, remember to set the height , otherwise the list content will appear outside the list content area, causing the pull-up loading event to fail , or the page jumping when sliding up and down .
    3. Data paging: The core point of data paging is whether it can accurately determine whether the data has been loaded. There are several ways to judge: A. The server returns the total number of pages. When the number of pages loaded with data is greater than or equal to the total number of pages, it means that the data is loaded. B. The total number of data returned by the server, when the obtained data is greater than or equal to the total number of data, it means that the data has been loaded. C. When the front-end requests each time, the server returns data with a fixed page size. When the number of returned data bars is smaller than the page size, it means that the data has been loaded. The above three methods, the method of judging the total number of pages and the total number of data pieces is reliable, and the method of judging that the number of returned data pieces is less than the page size is not accurate enough (because when the server is abnormal, a certain return If the number of data bars is less than the page size, it will be judged that the data has been loaded).
    4. Classic bug . Scenario: There are multiple tabs at the top of a page. When you click to switch tabs, the same page is shared, but the data is refreshed (with paging).

      When the tab is quickly clicked to switch, a bug in which the data of two tabs are displayed on the same page (multi-threaded concurrency) is generated.

The reason for the bug: When the tab is switched, because the interface request is asynchronous, the data of item-A is still processed in the response, and the request of item-B is sent, and item-B just reads the item-A's this.page += 1 page, so the data splicing logic of page > 1 is executed in the response of item-B, resulting in the data splicing of the two items now in the page of item-B.
Solution: 1.) Put the operation of adding one page to the method of pulling up to load more. 2.) Use separate page and list variables for each tab-item. This way there will be no out-of-the-box concurrency issues.

蓝光95
210 声望16 粉丝

一名从业多年的软件开发者,做过5年的iOS开发,做过一年的react-native开发,有iOS性能优化经验,IM开发经验,会小程序的开发,现在在昆明从事移动前端开发的工作。