• 优化:封装组件


    1、小程序 封装请求 判断 状态不是200 ,跳转页面

    export function request(options) {
        // 获取设备信息
        let versionType = global.globalData.versionType
            // 获取小程序版本信息
        let accountType = global.globalData.accountInfo
        let token = global.globalData.token;
        let userInfo = global.globalData.userInfo;
        let needToken = options.needToken == false ? false : true
        let needUid = options.needUid == true ? true : false
            // 合并设备信息和小程序版本号信息
    
        let miniAccount = Object.assign({}, versionType, accountType)
        global.globalData.miniAccount = miniAccount
    
        return new Promise((resolve, reject) => {
            wx.getNetworkType({
                success(ress) {
                    const networkType = ress.networkType
                    if (networkType != 'none') {
                        if (!token && needToken) {
                            console.log('token is null');
                        }
                        if (token && needToken) {
                            options.data.token = token;
                        }
                        if (userInfo && userInfo.id) {
                            if (userInfo.user_type) {
                                options.data.wid = userInfo.id;
                            } else if (!needUid) {
                                options.data.uid = userInfo.id;
                            }
                        }
                        let show = options.showLoading == true ? true : false;
                        if (show) {
                            mpvue.showLoading();
                        }
                        let needGetUserInfo = options.needUserInfo == false ? false : true
                        options.data.deviceInfo = JSON.stringify(miniAccount)
                        options.data.reqestType = 'miniProgram'
                            // if (needGetUserInfo) {
    
                        // }
                        mpvue.request({
                            url: options.url.indexOf('http') > -1 ? options.url : baseUrl + options.url,
                            data: options.data,
                            method: options.method || 'POST',
                            header: {
                                'content-type': 'application/json'
                            },
                            success(res) {
                                resolve(formatResponse(res))
                                if (show) {
                                    mpvue.hideLoading()
                                }
                            }
                        })
    
                    } else {
                        mpvue.showToast({
                            icon: 'none',
                            title: '网络连接失败,请检查网络后重试!'
                        });
                        reject('无网络')
                    }
                }
            })
        })
    }
    
    function formatResponse(result) {
        let code = result.statusCode
        let msg = ''
        if (code === 200) {
            if (!result.data.status) {
                if (result.data && result.data.data && result.data.data.code == 10001) {
                    mpvue.showToast({
                        icon: 'none',
                        title: result.data.msg
                    });
                    // mpvue.removeStorageSync('user_info.id')
                    delete global.globalData.userInfo.id
                    mpvue.setStorageSync('user_info', global.globalData.userInfo)
                    wx.removeStorageSync('token')
                    wx.removeStorageSync('hasLogin')
                    setTimeout(() => {
                        mpvue.redirectTo({ url: '/pages/auth/main' })
                    }, 1500)
    
    
                }
            }
            return result.data
        } else {
            return msg = '服务器异常'
        }
    }

    2、公众号用户授权,封装授权方法

    export default {
      data() {
        return {
          wxHasAuthorize: false,
          wxUserInfo: {},
          dxUserInfo: {},
          state: '',
          id: '',
          payId: '',
          entity: {
            domain: ''
          },
          dataInfo: {},
          url: ''
        }
    },
      beforeRouteEnter(to, from, next) {
        next(vm => {
          vm.url = to.path
          if (vm.url === '/red_packet/wechat' || vm.url === '/command_red_packet/home' || vm.url === '/command_red_packet/home/') {
            return
          }
          if (!from.name) {
            return // 表示初次扫码进入
          }
          setTimeout(() => {
            vm.vmaInit(isIOS && to.path !== location.pathname ? (location.origin + to.fullPath) : location.href, vm.payId).then(() => {
              vm.hideAllNonBaseMenuItem()
            })
          })
        })
      },
      mounted() {
        this.entity.domain = location.hostname
      },
    methods: {
     async wxAuthorize() {
          const {
            code,
            state,
            payId
          } = this.$route.query
          if (!this.wxHasAuthorize) {
            if (!code) {
              this.wxAuthorizeUrl()
            } else {
              await this.getWXUser(code).then(async wxUserInfo => {
                this.wxHasAuthorize = true
                this.wxUserInfo = wxUserInfo || {}
                await this.wxReady(wxUserInfo, state, payId)
                // this.getShare()
                // 测试
              }, error => {
                // code过期时,刷新当前地址,重新授权
                if (error.response && error.response.data && error.response.data.code === 'CODE_INVALID') {
                  this.$confirm(error.response.data.message, '提示', {
                    confirmButtonText: '确定',
                    showCancelButton: false,
                    type: 'warning'
                  }).then(() => {
                    // location.assign(this.getWXRefreshURI(state, payId))
                    let pageUrl = this.getWXRefreshURI(state, payId)
                    window.location.replace(pageUrl)
                  })
                } else {
                  handleException({
                    status: error.response.status,
                    message: error.message,
                    stack: error.stack
                  })
                }
              })
            }
          } else {
            await this.wxReady(this.wxUserInfo, state)
            // this.getShare()
          }
        },
        async wxAuthorizeUrl(url = location.href) {
          await commonApi.getWXAuthoriteUrl({
            url,
            state: this.state,
            payId: this.payId
          }).then(wxUrl => {
            window.location.replace(wxUrl)
          })
        },
        /**
         * 获取微信用户信息
         * @param {*} code
         */
        getWXUser(code) {
          return commonApi.getWXUserInfo({
            code
          })
        },
        getWXRefreshURI(state, payId) {
          return location.origin + location.pathname + '?id=' + state + '&payId=' + payId
        },
    }
    export function handleException({
      status,
      message,
      stack
    }) {
      if (isDev) {
        MessageBox({
          title: message || '系统提示',
          message: `<div style='max-height: 250px; overflow: auto;'>${stack}</div>`,
          type: 'error',
          showClose: true,
          dangerouslyUseHTMLString: true,
          duration: 15,
          callback(action, instance) {}
        })
      } else {
        MessageBox({
          title: '系统提示',
          message: '服务繁忙,请稍后再试',
          type: 'error',
          showClose: true,
          dangerouslyUseHTMLString: true,
          duration: 15,
          callback(action, instance) {}
        })
      }
    }

    3、三元判断来封装展示,隐藏蒙层

    <div id="btn_servering" class="btn_agreen mt_8" @click="showMc">继续服务</div>
            <!-- 蒙层 -->
            <div id="mc" class="mc_wrap" @click="showMc" v-if="isShow">
                <div class="mc_detail"><img src="@/assets/images/auth/mc.png" alt=""></div>
            </div>
      data() {
        return {
          isShow: 0
        }
      },
        showMc() {
          this.isShow = this.isShow === 0 ? 1 : 0
        }

    4、封装弹框展示传值(微客服--右击好友)

    2、微控后台 封装 展示用户信息(多处用到用户信息),封装成组件传值展示

    3、多出调用模板消息(小程序,快捷语等),进行封装。

  • 相关阅读:
    BZOJ#2820. YY的GCD
    BZOJ#3771. Triple(FFT+生成函数)
    BZOJ#4503. 两个串
    HDU#4609. 3-idiots
    UVA 12298 Super Poker II(FFT+母函数)
    HDU#1402. A×B
    树状数组的区间修改与区间查修
    COCI. DIFERENCIJA(序列处理中的小技巧)
    dt.select默认不区分大小写
    缓存,缓存算法和缓存框架
  • 原文地址:https://www.cnblogs.com/lpp-11-15/p/13265813.html
Copyright © 2020-2023  润新知