开启辅助访问 切换到宽版

精易论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

用微信号发送消息登录论坛

新人指南 邀请好友注册 - 我关注人的新帖 教你赚取精币 - 每日签到


求职/招聘- 论坛接单- 开发者大厅

论坛版规 总版规 - 建议/投诉 - 应聘版主 - 精华帖总集 积分说明 - 禁言标准 - 有奖举报

查看: 4872|回复: 2
收起左侧

[交流] uniapp VX小程序总结

[复制链接]
发表于 2021-11-3 11:16:04 | 显示全部楼层 |阅读模式   广东省揭阳市
本帖最后由 陆先森 于 2021-11-3 11:26 编辑

技术栈

  • uniapp、高德地图、短信、echarts

注意事项

域名配置


  • 图片资源放置服务器

过滤方法

性别

/**
* 性别(1:男,2:女)
*/
export function sexTypeToStr(type) {
    let str = '';

    if (type == 1) {
        str = '男';
    } else if (type == 2) {
        str = '女';
    }

    return str;
}

金额

/**
* 金额格式化
*/
export function formatPrice(value) {
    let val = '';

    if (value == '' || value === undefined ||value == null) {
        val = '0.00';
    } else {
        val = Number(value).toFixed(2);
    }
    return val;
}

格式验证

/*!
* 正则验证
*/
export default {
    // 正则
    empeyReg: /^[ ]*$/g, // 全空格正则
    spaceReg: /\s+/g, // 包含空格正则
    enReg: /^[a-zA-Z]*$/, // 英文正则
    cnReg: /^[\u0391-\uFFE5]+$/, // 中文正则
    numberReg: /^[0-9]+$/, // 数字正则
    enOrNumReg: /^[0-9a-zA-Z]*$/, // 英文数字组合正则
    priceReg: /^[0-9]+([.]{1}[0-9]{1,2})?$/, // 价格正则
    negativePriceReg: /^[0-9]+([.]{1}[0-9]{1,2})?$/, // 支持正负数价格正则
    telReg: /^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/, // 电话正则
    mobileReg: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, // 手机正则
    emailReg: /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/, // 邮箱正则

    /**
     * 验证表单是否有效
     * @param {string} value 值
     * @param {Array} rules 规则列表
     * @Return {boolean}
     */   
    valid(rules = []) {
        // 判断是否有设置表单规则
        if (!rules.length) {
            return {
                status: false,
                message: '未设置表单规则'         
            }            
        }   

        //----------------------------------------------------------
        // 遍历表单规则
        //----------------------------------------------------------
        for (let item of rules) {
            // 判断是否有设置表单验证规则
            if (this.isUndefined(item.rules)) {
                return {
                    status: false,
                    message: '未设置表单验证规则'         
                }            
            }

            //----------------------------------------------------------
            // 遍历表单验证规则
            //----------------------------------------------------------
            for (let itemRules of item.rules) {
                // 如果是NULL、undefined转字符串空
                item.value = item.value === 'null' || item.value === undefined ? '' : item.value;

                // 验证值是否全是空格
                if (item.value.length >= 1 && this.empeyReg.test(item.value) === true) {
                    return {
                        status: false,
                        message: '不能全部为空格'
                    };

                    break;
                }

                // 如果自定义验证函数存在,不验证规则
                if (!this.isUndefined(itemRules.validator)) {
                    const validate = itemRules.validator(itemRules.value, (message) => {
                        if (!this.isUndefined(message)) {
                            return {
                                status: false,
                                message: message
                            };
                        } else {
                            return {
                                status: true,
                                message: '验证通过'
                            };
                        }
                    });

                    if (!this.isUndefined(validate) && !validate.status) {
                        return {
                            status: validate.status,
                            message: validate.message
                        }

                        break;                           
                    }
                } else {
                    // 是否必填
                    if (!this.isUndefined(itemRules.required) && itemRules.required == true && item.value === '') {
                        return {
                            status: false,
                            message: this.isUndefined(itemRules.message) ? '不能为空' : itemRules.message
                        }

                        break;
                    }

                    // 长度最小、最大字符范围
                    if (!this.isUndefined(itemRules.min) && !this.isUndefined(itemRules.max) && item.value < itemRules.min && item.value > itemRules.max) {
                        return {
                            status: false,
                            message: this.isUndefined(itemRules.message) ? `长度${itemRules.min}到${itemRules.max}位` + itemRules.max : itemRules.message
                        }

                        break;
                    } else if (!this.isUndefined(itemRules.min) && item.value.length < itemRules.min) {
                        return {
                            status: false,
                            message: this.isUndefined(itemRules.message) ? '最小长度不能小于' + itemRules.min : itemRules.message
                        }

                        break;
                    } else if (!this.isUndefined(itemRules.max) && item.value.length > itemRules.max) {
                        return {
                            status: false,
                            message: this.isUndefined(itemRules.message) ? '最大长度不能大于' + itemRules.max : itemRules.message
                        }

                        break;
                    }

                    // 验证类型
                    if (!this.isUndefined(itemRules.type) && item.value !== '') {
                        // 是否整型数字
                        if (itemRules.type === 'number') {
                            console.log(item.value);

                            const valid = this.isNumber(item.value);

                            if (!valid) {
                                return {
                                    status: valid,
                                    message: this.isUndefined(itemRules.message) ? '必须是数字' : itemRules.message
                                }

                                break;                           
                            }                       
                        }

                        // 是否价格格式,不支持负数
                        if (itemRules.type === 'price') {
                            const valid = this.isPrice(item.value);

                            if (!valid) {
                                return {
                                    status: valid,
                                    message: this.isUndefined(itemRules.message) ? '金额格式不对' : itemRules.message
                                }

                                break;                           
                            }                       
                        }   

                        // 是否是电话号码
                        if (itemRules.type === 'tel') {
                            const valid = this.isTel(item.value);

                            if (!valid) {
                                return {
                                    status: valid,
                                    message: this.isUndefined(itemRules.message) ? '电话号码格式不正确' : itemRules.message
                                }

                                break;                           
                            }                     
                        }                    

                        // 是否是手机号码
                        if (itemRules.type === 'mobile') {
                            const valid = this.isMobile(item.value);

                            if (!valid) {
                                return {
                                    status: valid,
                                    message: this.isUndefined(itemRules.message) ? '手机号码格式不正确' : itemRules.message
                                }

                                break;                           
                            }                       
                        }                    

                        // 是否是邮箱
                        if (itemRules.type === 'email') {
                            const valid = this.isEmail(item.value);

                            if (!valid) {
                                return {
                                    status: valid,
                                    message: this.isUndefined(itemRules.message) ? '邮箱格式不正确' : itemRules.message
                                }

                                break;                           
                            }                     
                        }

                        // 是否是身份证号码
                        if (itemRules.type === 'IDCard') {
                            const validate = this.isIdentityCard(item.value);

                            if (!validate.status) {
                                return {
                                    status: validate.status,
                                    message: validate.message
                                }

                                break;                           
                            }                       
                        }

                        // 值两边是否有空格
                        if (itemRules.type === 'trim') {
                            if (item.value != '' && item.value.slice(0, 1) === ' ' || item.value.slice(-1) === ' ') {
                                return {
                                    status: false,
                                    message: this.isUndefined(itemRules.message) ? '两边不能有空格' : itemRules.message
                                }

                                break;                           
                            }                       
                        }

                        // 值里面不能包含空格
                        if (itemRules.type === 'space') {
                            if (this.noSpacesReg.test(item.value)) {
                                return {
                                    status: false,
                                    message: this.isUndefined(itemRules.message) ? '不能包含空格' : itemRules.message
                                }

                                break;                             
                            }                                   
                        }

                        // 是否英文字母
                        if (itemRules.type === 'en') {
                            const valid = this.isEN(item.value);

                            if (!valid) {
                                return {
                                    status: valid,
                                    message: this.isUndefined(itemRules.message) ? '必须是英文字母' : itemRules.message
                                }

                                break;                             
                            }                                   
                        }

                        // 是否中文汉字
                        if (itemRules.type === 'cn') {
                            const valid = this.isCN(item.value);

                            if (!valid) {
                                return {
                                    status: valid,
                                    message: this.isUndefined(itemRules.message) ? '必须是中文汉字' : itemRules.message
                                }

                                break;                             
                            }                                   
                        }   

                        // 是否英文数字
                        if (itemRules.type === 'enOrNum') {
                            const valid = this.isENOrNum(item.value);

                            if (!valid) {
                                return {
                                    status: valid,
                                    message: this.isUndefined(itemRules.message) ? '必须是英文数字组合' : itemRules.message
                                }

                                break;                             
                            }                              
                        }                        
                    }                  
                }               
            }
        }

        return {
            status: true,
            message: '通过'           
        }
    },
    isUndefined(value) {
        return value === undefined;
    },
    /**
     * 是否整型数字
     * @param {int} value 值
     * @return {boolean}
     */         
        isNumber(value) {
                return this.numberReg.test(value);
        },

    /**
     * 是否价格格式,不支持负数
     * @param {string} value 值
     * @return {boolean}
     */        
        isPrice(value) {               
                return this.priceReg.test(value);
        },
    /**
     * 是否是价格格式,支持正负数
     * @param {string} value 值
     * @return {boolean}
     */
    isNegativePrice(value) {
        return negativePriceReg.test(value);
    },
    /**
     * 是否是电话号码
     * @param {string} value 值
     * @return {boolean}
     */
    isTel(value) {
        return this.telReg.test(value);
    },
    /**
     * 是否是手机号码
     * @param {string} value 值
     * @return {boolean}
     */
    isMobile(value) {
        return this.mobileReg.test(value);
    },
    /**
     * 是否是邮箱
     * @param {string} value 值
     * @return {boolean}
     */
    isEmail(value) {
        return this.emailReg.test(value);
    },
    /**
     * 是否英文字母
     * @param {string} value 值
     * @return {boolean}
     */
    isEN(value) {
        return this.enReg.test(value);
    },
    /**
     * 是否中文汉字
     * @param {string} value 值
     * @return {boolean}
     */
    isCN(value) {
        return this.cnReg.test(value);
    },   
    /**
     * 是否英文数字组合
     * @param {string} value 值
     * @return {boolean}
     */
    isENOrNum(value) {
        return this.enOrNumReg.test(value);
    },
    /**
     * 判断是否是身份证
     * @param {string} code
     * @return: {Object}
     */
    isIdentityCard(code) {
        let list = [];
        let result = false;
        let msg = '';

        const city = {
            11: "北京",
            12: "天津",
            13: "河北",
            14: "山西",
            15: "内蒙古",
            21: "辽宁",
            22: "吉林",
            23: "黑龙江 ",
            31: "上海",
            32: "江苏",
            33: "浙江",
            34: "安徽",
            35: "福建",
            36: "江西",
            37: "山东",
            41: "河南",
            42: "湖北 ",
            43: "湖南",
            44: "广东",
            45: "广西",
            46: "海南",
            50: "重庆",
            51: "四川",
            52: "贵州",
            53: "云南",
            54: "西藏 ",
            61: "陕西",
            62: "甘肃",
            63: "青海",
            64: "宁夏",
            65: "新疆",
            71: "台湾",
            81: "香港",
            82: "澳门",
            91: "国外 "
        };

        if (code != '') {
            if (code.length == 18) {
                if (!code || !/(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(code)) {
                    msg = "证件号码格式错误";
                } else if (!city[code.substr(0, 2)]) {
                    msg = "地址编码错误";
                } else {
                    // 18位身份证需要验证最后一位校验位
                    code = code.split('');

                    // 加权因子
                    const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];

                    // 校验位
                    let parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2, 'x'];
                    let sum = 0;
                    let ai = 0;
                    let wi = 0;

                    for (let i = 0; i < 17; i++) {
                        ai = code;
                        wi = factor;
                        sum += ai * wi;
                    }

                    if (parity[sum % 11] != code[17]) {
                        msg = "证件号码校验错误";
                    } else {
                        result = true;
                    }

                }
            } else {
                msg = "证件号码长度不能少于18位";
            }

        } else {
            msg = "证件号码不能为空";
        }

        return {
            status: result,
            message: msg
        };
    }
};

Toast提示

/*!
* Toast轻提示
*/
export default {
    /**
     * 显示提示框
     * @param {String} value
     * @return {void}
     */
    show(value) {
        uni.showToast({
                title: value,
                icon: 'none',
                duration: 2000
        });
    },
    /**
     * 隐藏提示框
     */
    clear() {
        uni.hideToast();
    },
    /**
     * 显示loading
     * @param {string, object} option 字符串或者对象选项
     * @return {void}
     */   
    showLoading(option) {
        if (typeof option === 'string') {
            const value = option;

                        uni.showLoading({
                                title: value
                        });
        } else {
                        uni.showLoading(option);   
        }
    },
    /**
     * 关闭loading
     */   
    clearLoading() {
        uni.hideLoading();
    }   
};

常用方法

格式化时间戳

/*!
* 常用公共函数
*/
export default {
    /*-------------------------------------------------------------------------------------
     | 常用函数
     |-------------------------------------------------------------------------------------
     */
    /**
     * 格式化时间戳
     * @param {int} times 时间戳
     * @param {string} format 格式
     * @return {string}
     */
    formatTime(times, format = '') {
        const today = new Date(times);
        const y = today.getFullYear();
        const m = (today.getMonth() + 1 < 10) ? '0' + (today.getMonth() + 1) : (today.getMonth() + 1);
        const d = (today.getDate() < 10) ? '0' + today.getDate() : today.getDate();
        const h = (today.getHours() < 10) ? '0' + today.getHours() : today.getHours();
        const i = (today.getMinutes() < 10) ? '0' + today.getMinutes() : today.getMinutes();
        const s = (today.getSeconds() < 10) ? '0' + today.getSeconds() : today.getSeconds();

        let time = '';

        if (format === '年-月') {
            time = y + '年' + m + '月';
        } else if (format === 'y-m-d h:i') {
            time = y + '-' + m + '-' + d + ' ' + h + ':' + i;
        } else if (format == 'y-m-d h:i:s') {
            time = y + '-' + m + '-' + d + ' ' + h + ':' + i + ':' + s;
        }else if (format === 'y-m-d') {
            time = y + '-' + m + '-' + d;
        } else if (format === 'y-m') {
            time = y + '-' + m;
        } else if (format === 'ymd') {
            time = y + '' + m + '' + d;
        } else if (format === 'd') {
            time = d;
        } else if (format === 'h:i') {
            time = h + ':' + i;
        } else if (format === 'h') {
            time = h;
        } else if (format === 'y') {
            time = y;
        } else {
            time = y + '-' + m + '-' + d;
        }

        return time;
    },

};

获取url

/*!
* 常用公共函数
*/
export default {
    /**
     * 获取URL参数
     * @param {string} paramName 参数
     * @return {string}
     */
    getParam(paramName) {
        const reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)", "i");

        if (window.location.hash.indexOf('=') >= 0) {
            const params = window.location.hash.split('?');
            const r = params[1].match(reg);

            if (r != null) return (r[2]); return '';
        } else {
            if (window.location.search.indexOf('=') >= 0) {
                const params = window.location.search.split('?');
                const r = params[1].match(reg);

                if (r != null) return (r[2]); return '';
            } else {
                return '';
            }         
        }
    },
}

对象按字母排序

/*!
* 常用公共函数
*/
export default {
/**
* 对象按字母排序
* @param {object} obj 参数
* @return {string}
*/
    objKeySort(obj) {
        // 创建一个新的对象,用于存放排好序新对象
        let newkey = Object.keys(obj).sort();

        // 创建一个新的对象,用于存放排好序的键值对
        let newObj = {};

        for (var i = 0; i < newkey.length; i++) {
            newObj[newkey] = obj[newkey]; //向新创建的对象中按照排好的顺序依次增加键值对
        }

        return newObj;
    },
}

时间格式化

//格式化时间格式
export const formatNumber = n => {
  //数字转字符串
  n = n.toString();
  //判断该数字是否为俩位数,如果不是就在前面加0(格式化)
  return n[1] ? n : "0" + n;
};

//获取当前年月日时分秒(格式化)
export const formatTime = date => {
  const year = date.getFullYear(); //获取年
  const month = date.getMonth() + 1; //获取月
  const day = date.getDate(); //获取日
  const hour = date.getHours(); //获取时
  const minute = date.getMinutes(); //获取分
  const second = date.getSeconds(); //获取秒

  //格式化
  return (
    [year, month, day].map(formatNumber).join("-") +
    " " +
    [hour, minute, second].map(formatNumber).join(":")
  );
};

操作本地Storage(切换微信号,隔离的)

/*!
* 本地存储
*/
export default {
    /**
     * 写入Storage
     * @param {String} key 值名称
     * @param {String} value 值
     * @return {void}
     */
    set(key, value) {
        uni.setStorageSync(key, value);
    },
    /**
     * 获取Storage
     * @param {String} key 值名称
     * @return {String}
     */
    get(key) {
        return uni.getStorageSync(key, key);
    },
    /**
     * 删除Storage
     * @param {String} key 值名称
     * @return {void}
     */
    remove(key) {      
        uni.removeStorageSync(key, key);
    }
};

数据请求(俩种)

uni-request模块

基本配置

import uniRequest from 'uni-request';

uniRequest.defaults.baseURL = 'https://dianligongsi001.hzsandao.com/index/apiwx';// api的base_url
uniRequest.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// 请求拦截
uniRequest.interceptors.request.use(
    request => {
        //配置基本信息   
        return request;
    },
    err => {
        console.log('请求失败');
        return Promise.reject(err);
    });

// 响应拦截
uniRequest.interceptors.response.use(function(response) {
    console.log('返回进入拦截成功')
    return Promise.resolve(response);
}, function(error) {
    console.log('返回进入拦截失败')
    return Promise.reject(error);
});

export default uniRequest;

请求方法配置

import request from '../utils/request.js';

//[post]请求
export function Post(url,data) {
     return request({
          url,
          data,
                  method: 'post',
        })
  }

flyio模块

配置(直接入口挂载在原型上)

/*!
* HTTP请求
*/
// #ifdef APP-PLUS
import Fly from 'flyio/dist/npm/wx'
// #endif
// #ifdef MP-WEIXIN
import Fly from 'flyio/dist/npm/wx'
// #endif
// #ifdef H5
import Fly from 'flyio/dist/npm/fly'
// #endif

import Config from '@/config';
import Storage from '@/utils/storage'; // 本地存储
import Toast from '@/utils/toast';

/*-------------------------------------------------------------------------------------
| 初始化
|-------------------------------------------------------------------------------------
*/
let baseURL = '';
const request = new Fly();

// 环境判断
switch (process.env.NODE_ENV) {
    case 'development':
        baseURL = Config.devURL;
        break;
    case 'production':
        baseURL = Config.proURL;
        break;

    default:   
}

// 请求前拦截器
request.interceptors.request.use((request) => {
        request.headers = {
                'content-type': 'application/x-www-form-urlencoded'
        }

        return request;
});

// 响应前拦截器
request.interceptors.response.use((request) => {
        const res = JSON.parse(request.data);

        if (res.status != 200) {
                Toast.show(res.message);
        }

        return request;
})

export default {
    /**
     * get方法
     * @param {string} url // 接口地址
     * @param {object} params // 参数对象
     * @return {Promise}
     */  
    get(url = '', params = {}) {
                // 设置需要携带的参数
                const initParams = {
                        token: Storage.get('token') == null ? '' : Storage.get('token')
                };

                // 合并参数
                const newParams = Object.assign(params, initParams);               

        // 返回响应数据
        return new Promise((resolve, reject) => {
                        request.get(baseURL + url, newParams)
                        .then(res => {
                                const data = JSON.parse(res.data);
                            resolve(data);
                        })
                        .catch(err => {
                                reject(err);
                        });
        });
    },        
    /**
     * post方法
     * @param {string} url // 接口地址
     * @param {object} params // 参数对象
     * @return {Promise}
     */  
    post(url = '', params = {}) {        
                // 设置需要携带的参数
                const initParams = {
                        token: Storage.get('token') == null ? '' : Storage.get('token')
                };

                // 合并参数
                const newParams = Object.assign(params, initParams);               

        // 返回响应数据
        return new Promise((resolve, reject) => {               
                        request.post(baseURL + url, newParams)
                        .then(res => {
                                const data = JSON.parse(res.data);
                            resolve(data);
                        })
                        .catch(err => {
                                reject(err);
                        });
        });
    },

};

分包配置

"pages": [
    //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages
         //主包
                {
                        "path": "pages/login/login",
                        "style": {
                                "navigationBarTitleText": "xxxx"
                        }
                },
    ],
"subPackages":[
        {
                        "root": "xx/", //分包---xxx
                        "pages":[
                                {
                                        "path": "xxx/xxx",
                                        "style": {
                                                "navigationBarTitleText": "xxxx",
                                                "usingComponents": {
                                                          //.....UI框架组件引入
                                                        }
                                        }
                                }
                        ]
                },
]

全局样式配置

"globalStyle": {
                "navigationBarTextStyle": "#fff",
                "navigationBarTitleText": "xxxx",
                "navigationBarBackgroundColor": "#006469",
                "backgroundColor": "#F8F8F8",
                "usingComponents": {
                         //.....UI框架组件引入
                        }
        }

权限控制

位置

"permission":{
            "scope.userLocation":{
              "desc":"你的位置信息将用于小程序位置接口的"//小程序调用位置信息权限
            }
          }

微信获取openid

// var url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&js_code=' + loginRes.code + '&grant_type=authorization_code';

页面传值

周期函数获取

//main
uni.navigateTo({
                                        url:'/xxx/xxx?xxx=xx'
                                })
//app
onLoad(option){
    //option.xxx
}

设置上一页变量或者调用上一页方法

var pages = getCurrentPages();
var currPage = pages[pages.length - 1]; //当前页面
var prevPage = pages[pages.length - 2]; //上一个页面
prevPage.$vm.getHistory();

地图

配置

import amap from '@/utils/amap-wx.js';

data(){
    return {
        amapPlugin:null,
        key:'xxxx',
    }
}
onLoad(){
        //配置地图的key
        this.amapPlugin = new amap.AMapWX({
            key: this.key
        });
        }

组件配置

<!--
* map 用到的属性
* @param width map宽度
* @param height map高度
* @param latitude 中心纬度
* @param longitude 中心经度
* @param scale 缩放级别,取值范围为5-18
* @param markers 标记点
* @param show-location 显示带有方向的当前定位点
* @param markertap 点击标记点时触发
-->

<map
                                style="width: 100%; height: 40vh;"
                                id="map4select"
                                :latitude="latitude"
                                :longitude="longitude"
                                scale="16"
                                show-location="true"
                                @markertap=markertap
                                @regionchange="regionchange">
                                                <cover-image class="cover-image" bindtap="my_location" src="xxxx" />
                                </map>        

获取周边数据

that.amapPlugin.getRegeo({
                                          location: 'xxx,xxx',
                                      success: function(data){
                          //....
                      }
})

返回最近的20的位置信息

this.amapPlugin.getPoiAround({
                                  location:'xxx,xxx',//指定搜索坐标周边poi
                                  success: function(data){
                                        //成功回调
                                        // data.poisData;
                                        //设置当前坐标(获取当前的详细数据)
                                  },
                                  fail: function(info){
                                        //失败回调
                                        // console.log(info)
                                  }
                                })

关键字搜索

this.amapPlugin.getInputtips({
                                        keywords :keywords,//关键词
                                        city:'0571',//限制省
                                        citylimit:true,//限制省
                                        success: function(data){
                                                // // console.log(data)
                                        }
                                })

获取当前的详细信息

that.amapPlugin.getRegeo({
                                          location: 'xxx,xxx',
                                      success: function(data){
                                        //成功回调

                                      },
                                      fail: function(info){
                                        //失败回调
                                        // console.log(info)
                                      }
                                    })

拖动地图事件

regionchange(e){
                                if (e.type == 'end' && (e.causedBy == 'scale' || e.causedBy == 'drag')) {
                                        var that = this;
                                        this.mapCtx = uni.createMapContext("map4select");
                                        this.mapCtx.getCenterLocation({
                                                type: 'gcj02',
                                                success: function (res) {
                                                                that.longitude=res.longitude;
                                                                that.latitude=res.latitude;
                                                        }
                                                })
                                        this.getPoiAround();//定位当前的周边数据
                                }
                        }

获取当前位置数据

uni.getLocation({
                type: 'gcj02',//标准
                success: function (res) {
                    // console.log(res,"nimei")
                    // that.longitude=res.longitude;
                    // that.latitude=res.latitude;
                },
                fail:function(info){
                    // console.log(info)
                },
                complete:function(){
                    // uni.hideLoading();
                }
            });

改变地图位置

  • 改变data的经纬度
  • 利用方法
    this.mapCtx.includePoints({  
                                                  padding: [10],  
                                                  points: [{  
                                                        latitude:'xxx',  
                                                        longitude:'xxx',  
                                                  }]  
                                                })

上传九张图片

//调起图片
                        sendphoto(){
                                let self=this;
                                uni.chooseImage({
                                          count: 9,
                                          sizeType: ['compressed'],//// sizeType:  original 原图,compressed 压缩图,默认二者都有
                                          sourceType: ['album', 'camera'],
                                          success(res) {
                                                // tempFilePath可以作为img标签的src属性显示图片
                                                const tempFilePaths = res.tempFilePaths;
                                                var successUp = 0; //成功
                                            var failUp = 0; //失败
                                            var length = res.tempFilePaths.length; //总数
                                            var count = 0; //第几张
                                            self.uploadOneByOne(res.tempFilePaths,successUp,failUp,count,length)
                                          }
                                        })
                        }

            /**
                          * 采用递归的方式上传多张
                          */
                         uploadOneByOne(imgPaths,successUp, failUp, count, length){
                           var that = this;
                           uni.showLoading({
                              title: '正在上传第'+(count+1)+'张',
                            })
                           uni.uploadFile({
                             url: 'xxxx', //仅为示例,非真实的接口地址
                             filePath: imgPaths[count],
                             name: 'photo',//示例,使用顺序给文件命名json名
                                 header: {
                                                "Content-Type": "multipart/form-data",
                                                'accept': 'application/json',
                                 },
                             success:function(e){
                                         var data=JSON.parse(e.data);
                                        that.imgList.push(data.url);
                                        console.log(that)
                               successUp++;//成功+1
                             },
                             fail:function(e){
                               failUp++;//失败+1
                             },
                             complete:function(e){
                               count++;//下一张
                               if(count == length){
                                 //上传完毕,作一下提示
                                 console.log('上传成功' + successUp + ',' + '失败' + failUp);
                                 uni.showToast({
                                   title: '上传成功' + successUp,
                                   icon: 'success',
                                   duration: 2000
                                 })
                               }else{
                                 //递归调用,上传下一张
                                         setTimeout(function() {
                                                 that.uploadOneByOne(imgPaths, successUp, failUp, count, length);
                                         }, 200);
                                 console.log('正在上传第' + count + '张');
                               }
                             }
                           })
                         }

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?注册

x

评分

参与人数 1好评 +1 精币 +1 收起 理由
执骨哟 + 1 + 1 这已经不止是扫盲贴了,已经喂到嘴里了都

查看全部评分

发表于 2022-5-9 23:09:26 | 显示全部楼层   江西省南昌市

支持~!感谢分享
回复 支持 反对

使用道具 举报

结帖率:100% (3/3)
发表于 2021-11-3 21:04:08 | 显示全部楼层   内蒙古自治区包头市
已经收藏!!!
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则 致发广告者

发布主题 收藏帖子 返回列表

sitemap| 易语言源码| 易语言教程| 易语言论坛| 诚聘英才| 易语言模块| 手机版| 广告投放| 精易论坛
拒绝任何人以任何形式在本论坛发表与中华人民共和国法律相抵触的言论,本站内容均为会员发表,并不代表精易立场!
论坛帖子内容仅用于技术交流学习和研究的目的,严禁用于非法目的,否则造成一切后果自负!如帖子内容侵害到你的权益,请联系我们!
防范网络诈骗,远离网络犯罪 违法和不良信息举报电话0663-3422125,QQ: 800073686,邮箱:800073686@b.qq.com
Powered by Discuz! X3.4 揭阳市揭东区精易科技有限公司 ( 粤ICP备12094385号-1) 粤公网安备 44522102000125 增值电信业务经营许可证 粤B2-20192173

快速回复 返回顶部 返回列表