微信小程序的一些小知识

732 阅读4分钟

这篇文章用来记录工作中开发微信小程序的一些小知识

1 通过code 获取openid session_key

    wx.login({
        success: res => {
            this.globalData.code = res.code //用户进入小程序后可以获取到 code 通过code传递给后台可以换回openid 
        }
    })

2 获取用户信息 现在授权需要用户点击按钮触发事件 通过 wx.getSetting可以判断用户的授权状态

    wx.getSetting({
        success: res => {
            if (res.authSetting['scope.userInfo']) {
                //如果授权过了才可以直接拿用户信息
                wx.getUserInfo({
                    success: function (res) {
                        //设置本地存储
                        wx.setStorageSync('userInfo', res.userInfo)
                    }
                })
            }
        }
    })

2.1 用户点击open-type为"getUserInfo"的button可以触发授权弹窗 这个按钮是否出现开发者需要自行判断

    <button class='btnnn' wx: if= "{{ !hasUserInfo}}" open - type="getUserInfo" bindgetuserinfo = "bindGetUserInfo" > 授权登录</button >
    bindGetUserInfo(e){
        if (e.detail.errMsg !== "getUserInfo:ok") {
            return
        }
        console.log('按钮返回的', e)
    }

2.2 微信开放能力 未授权的情况也可以拿到一部分的用户信息 如下 昵称和头像

        <open-data type="userNickName"></open-data> 
        <open-data type="userAvatarUrl"></open-data>

3 swiper切换 联动scroll-view

    <swiper class='main' bindchange='pagechange' current='{{currentIndex}}'>
    </swiper>

    <scroll-view class='sw' scroll-x="true">
        <view class="{{index == currentIndex?'item select':'item '}}" bindtap='titleClick' data-idx='{{index}}' wx: for="{{ list }}" wx:key="{{ index }}">
            <text>{{ item }}</text>
         </view>
    </scroll - view>
    
    // swiper切换时会调用
    pagechange: function(e) {
        console.log(e.detail.current)
        if ("touch" === e.detail.source) {
          let currentPageIndex = this.data.currentIndex
          currentPageIndex = e.detail.current
          this.setData({
            currentIndex: currentPageIndex
          })
        }
    },

    //  点击选项卡列表时调用
    titleClick: function(e) {
        console.log(e.currentTarget.dataset.idx)
        let currentPageIndex =
            this.setData({
            //拿到当前索引并动态改变
            currentIndex: e.currentTarget.dataset.idx
        })
    }

4 分享onShareAppMessage 在生成页面是已经定义过是个空函数 注意不要直接复制这段代码 要先删掉空的函数 否则重复定义

<button open-type='share'></button>
onShareAppMessage: function(res) {
    console.log(res)
    // 来自按钮的
    if (res.from === 'button') {
      return {
        title: '按钮点击的', //分享的标题
        imageUrl: "/images/***.png", //分享的图片
        path: '/pages/my/**/**?boosid=' + app.globalData.openid, //自定义分享的路径
        success: function(res) {
          console.log('成功', res)
        }
      }
    } else {
      // 来自右上角的
      return {
        title: '右上角分享的',
        imageUrl: "/images/***.png",
        path: '/pages/index/index',
        success: function(res) {
          console.log('成功', res)
        }
      }
    }
  }

5 保存图片到本地 思路先判断有无相册权限 “scope.writePhotosAlbum” 然后下载图片 wx.getImageInfo({}) 然后保存 wx.saveImageToPhotosAlbum({})

  // 生成二维码
  shengchengZSM() {
    var that = this
    wx.getSetting({
      success: (res) => {
        console.log(res)
        // 如果有保存到相册的权限直接下载
        if (res.authSetting["scope.writePhotosAlbum"]) {
          wx.showLoading({
            title: '正在加载...',
            mask: true
          });
          that.getZSM()
          // 否则申请权限
        } else {
          wx.authorize({
            scope: "scope.writePhotosAlbum",
            success: () => {
              wx.showLoading({
                title: '正在加载...',
                mask: true
              });
              // 申请成功开始下载
              that.getZSM()
            },
            fail: () => {
            // 申请失败 提示用户打开授权管理页面
              wx.showModal({
                title: "提示",
                content: "若点击不授权,将无法使用保存功能",
                cancelText: "不授权",
                cancelColor: "#999",
                confirmText: "去授权",
                confirmColor: "#FF5846",
                success: (res) => {
                // 如果用户同意 打开授权管理页面
                  if (res.confirm) {
                    wx.openSetting({
                      success: (res) => {
                      // 从授权管理返回时 判断是否有保存相册权限
                        if (res.authSetting["scope.writePhotosAlbum"]) {
                          wx.showLoading({
                            title: '正在加载...',
                            mask: true
                          });
                          that.getZSM()
                        }
                      }
                    })
                  }
                }
              })
            }
          })
        }
      }
    })
  },
  // 发起生成二维码的请求获取下载链接
  getZSM() {
    var that = this
    ajax.get("/appPraiseClient/findUserQRcode", {
      clientId: app.globalData.openid,
      pageUrl: "pages/my/zshome/zshome",
      bgUrl: that.nowImginfo.backgroundImg,
      fontColor: that.nowImginfo.color || "#333",
      userName: that.userInfo.name ? that.userInfo.name : that.userInfo.wxname,
      thank: that.userInfo.guide
    }).then((res) => {
      console.log(res, '生成二维码的路径')
      that.loadZSM(res.data.obj)
    }, (err) => {
      console.log(err, "生成二维码路径失败");
      wx.hideLoading()
      wx.showToast({
        title: "生成二维码连接失败!",
        icon: "none",
        mask: true
      })
    })
  },
  // 下载返回的二维码路径
  loadZSM(src) {
    var that = this
    wx.getImageInfo({
      src: that.imgurl + src,
      success: (res) => {
        console.log(res, "下载二维码");
        that.saveZSM(res)
      },
      fail: (err) => {
        console.log(err, "下载二维码失败");
        wx.hideLoading()
        wx.showToast({
          title: "下载二维码失败!",
          icon: "none",
          mask: true
        })
      }
    })
  },
  // 保存下载好的二维码
  saveZSM(src) {
    wx.saveImageToPhotosAlbum({
      filePath: src.path,
      success: (res) => {
        console.log("保存成功", res);
        wx.hideLoading()
        wx.showToast({
          title: "保存二维码成功!",
          icon: "none",
          mask: true
        })
      },
      fail: (err) => {
        console.log("保存失败", err);
        wx.hideLoading()
        wx.showToast({
          title: "保存二维码失败!",
          icon: "none",
          mask: true
        })
      }
    })
  },

5.1 常见的权限

 scope: 'scope.writePhotosAlbum' // 保存到相册
 scope:'scope' // 录音权限

6 recorderManager录音机 和 innerAudioContext播放器 相关

    // 获取录音实例
    const recorderManager = wx.getRecorderManager()
    const innerAudioContext = wx.createInnerAudioContext()
    
    // 开始录音
    recorderManager.start({format:"mp3"})
    // 停止录音
    recorderManager.stop()
    
    // 开始播放
    innerAudioContext.play() 
    // 暂停播放
    innerAudioContext.pause()
    
    // 录音机的回调函数只需注册一次即可
    recorderManager.onStop((res)=>{ 
        console.log(res,this.tipsbox,"录音机结束回调");
	this.setaudio=res.tempFilePath // 在录音结束时候保存临时路径
	innerAudioContext.src=res.tempFilePath // 在录音结束给播放器src赋值
    })
    // 播放器的回调函数只需注册一次即可
    innerAudioContext.onEnded((res)=>{
	console.log("自然播放完毕回调..",this.tipsbox);
	this.isbofang=false 
    }) 

7 上传文件

 wx.uploadFile({
    url: "接口地址",
    filePath: this.data.setimgurl[0], // 文件路径
    method: "POST",
    name: 'files',
    header: {
      "Content-Type": "multipart/form-data",
      'accept': 'application/json'
    },
    formData: {
      //其他额外的formdata,可不写
      openid: app.globalData.openid,
      thankType: 2,
    },
    success: (res) => { 

      wx.hideLoading()
      if (res.data.returnCode == 1) {
        app.globalData.gxtype = 5
        wx.showToast({
          title: '保存成功',
          icon: 'none',
          mask: true,
          success: function(res) {},
          fail: function(res) {},
          complete: function(res) {},
        })
      }
    },
    fail: (err) => {
      console.log('失败上传', err)
      wx.hideLoading()
      wx.showToast({
        title: '保存失败,稍后再试!',
        icon: 'none',
        mask: true,
      })
    }
  })