1.10 设置

作者: 追梦小乐 | 来源:发表于2018-12-11 09:24 被阅读46次

    1、设置页面

    1.1 新建setting页面

    app.json
    image.png
    image.png

    1.2 在tab选项卡中加入setting页面

    app.json
    image.png image.png

    1.3 setting页面的骨架

    setting.wxml
    <view class="container">
      <view class="category-item personal-info">
        <view class="user-avatar">
          <image src="{{userInfo.avatarUrl}}"></image>
        </view>
        <view class="user-name">
          <view class="user-nickname">
            <text>{{userInfo.nickName}}</text>
          </view>
          <view class="user-locaiton">
            <text>所在地:{{userInfo.city}}</text>
          </view>
        </view>
      </view>
      <view class="category-item">
        <block wx:for="{{cache}}">
          <view class="detail-item" catchtap="{{item.tap}}">
            <image src="{{item.iconurl}}"></image>
            <text>{{item.title}}</text>
            <view class="detail-item-btn"></view>
          </view>
        </block>
      </view>
      <view class="category-item">
        <block wx:for="{{device}}">
          <view class="detail-item" catchtap="{{item.tap}}">
            <image src="{{item.iconurl}}"></image>
            <text>{{item.title}}</text>
            <view class="detail-item-btn"></view>
          </view>
        </block>
      </view>
      <view class="category-item">
        <block wx:for="{{api}}">
          <view class="detail-item" catchtap="{{item.tap}}">
            <image src="{{item.iconurl}}"></image>
            <text>{{item.title}}</text>
            <view class="detail-item-btn"></view>
          </view>
        </block>
      </view>
      <view class="category-item">
        <block wx:for="{{others}}">
          <view class="detail-item" catchtap="{{item.tap}}">
            <image src="{{item.iconurl}}"></image>
            <text>{{item.title}}</text>
            <view class="detail-item-btn"></view>
          </view>
        </block>
      </view>
    
    </view>
    
    

    由于每个面板下的子项较多,且有可能经常添加子项,因此没有直接将子项硬编码,而是采用了一种配置式的编写方法。每个项目下的子项目内容都将在js文件中配置,然后通过数据绑定和列表渲染动态的填充到wxml中

    1.4 setting页面的样式

    setting.wxss
    .container {
        background-color: #efeff4;
        width: 100%;
        height: 100%;
        flex-direction: column;
        display: flex;
        align-items: center;
        min-height: 100vh;
    }
    .category-item {
        width: 100%;
        margin: 20rpx 0;
        border-top: 1rpx solid #d9d9d9;
        border-bottom: 1rpx solid #d9d9d9;
        background-color: #fff;
    }
    .category-item.personal-info {
        height: 130rpx;
        display: flex;
        padding: 20rpx 0;
    }
    .category-item.personal-info .user-avatar {
        margin: 0 30rpx;
        width: 130rpx;
        height: 130rpx;
        position: relative;
    }
    .category-item.personal-info .user-avatar image {
        vertical-align: top;
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left:0;
        border-radius: 2rpx;
    }
    .category-item.personal-info .user-name {
        margin-right: 30rpx;
        flex: 1;
        padding-top: 10rpx;
    }
    .detail-item{
        display: flex;
        margin-left: 30rpx;
        border-bottom: 1px solid RGBA(217, 217, 217, .4);
        height:85rpx;
        align-items: center;
    }
    .detail-item:last-child{
        border-bottom:none;
    }
    .detail-item image{
        height: 40rpx;
        width:40rpx;
    
    }
    .detail-item text{
        color:#7F8389;
        font-size:24rpx;
        flex:1;
        margin-left: 30rpx;
    }
    .detail-item .detail-item-btn{
        width: 50rpx;
        color: #d9d9d9;
        height: 40rpx;
        margin-right: 20rpx;
        text-align: center;
    }
    .detail-item .detail-item-btn::after{
        display: inline-block;
        content:'';
        width: 16rpx;
        height: 16rpx;
        color: #d9d9d9;
        margin-top: 8rpx;
        border:3rpx #d9d9d9 solid;
        border-top-color:transparent;
        border-left-color:transparent;
        transform: rotate(-45deg);
    }
    

    1.5 setting页面的配置

    setting.js
    Page({
    
      /**
       * 页面的初始数据
       */
      data: {
        cache: [
          { iconurl: '/images/icon/wx_app_clear.png', title: '缓存清理', tap: 'clearCache' }
        ],
        device: [
          { iconurl: '/images/icon/wx_app_cellphone.png', title: '系统信息', tap: 'showSystemInfo' },
          { iconurl: '/images/icon/wx_app_network.png', title: '网络状态', tap: 'showNetWork' },
          { iconurl: '/images/icon/wx_app_location.png', title: '地图显示', tap: 'showMap' },
          { iconurl: '/images/icon/wx_app_compass.png', title: '指南针', tap: 'showCompass' },
          { iconurl: '/images/icon/wx_app_lonlat.png', title: '当前位置、速度', tap: 'showLonLat' },
          { iconurl: '/images/icon/wx_app_shake.png', title: '摇一摇', tap: 'shake' },
          { iconurl: '/images/icon/wx_app_scan_code.png', title: '二维码', tap: 'scanQRCode' }
        ],
        api: [
          { iconurl: '/images/icon/wx_app_list.png', title: '下载pdf、word文档', tap: 'downloadDocumentList' },
          { iconurl: '', title: '用户登陆', tap: 'login' },
          { iconurl: '', title: '校验用户信息', tap: 'check' },
          { iconurl: '', title: '获取用户加密信息', tap: 'decrypted' },
          { iconurl: '', title: '模板消息', tap: 'tplMessage' },
          { iconurl: '', title: '微信支付', tap: 'wxPay' }
        ],
        others: [
          { iconurl: '', title: 'wx:key示例', tap: 'showWxKeyDemo' },
          { iconurl: '', title: 'scroll-view高级用法演示', tap: 'showScrollViewDemo' }
        ],
      },
    
      /**
       * 生命周期函数--监听页面加载
       */
      onLoad: function (options) {
      
      },
    
      /**
       * 生命周期函数--监听页面初次渲染完成
       */
      onReady: function () {
      
      },
    
      /**
       * 生命周期函数--监听页面显示
       */
      onShow: function () {
      
      },
    
      /**
       * 生命周期函数--监听页面隐藏
       */
      onHide: function () {
      
      },
    
      /**
       * 生命周期函数--监听页面卸载
       */
      onUnload: function () {
      
      },
    
      /**
       * 页面相关事件处理函数--监听用户下拉动作
       */
      onPullDownRefresh: function () {
      
      },
    
      /**
       * 页面上拉触底事件的处理函数
       */
      onReachBottom: function () {
      
      },
    
      /**
       * 用户点击右上角分享
       */
      onShareAppMessage: function () {
      
      }
    })
    
    image.png

    1.6 setting页面导航栏配置

    setting.json
    {
      "navigationBarTextStyle": "white",
      "navigationBarTitleText": "设置"
    }
    
    image.png

    2、获取用户基本信息

    2.1 新建g_userInfo全局变量

    app.js
    image.png

    2.2 获取用户基本信息

    image.png

    因为小程序API的更新,需要用户主动触发授权才可以获取用户的基本信息,因此将授权工作放在欢迎页面的点击按钮上


    image.png
    welcome.js
    
    var app = getApp();
    
    Page({
    
      /**
       * 页面的初始数据
       */
      data: {
        canIUse: wx.canIUse('button.open-type.getUserInfo'),//检查有没有使用权限
        loginCode:null
      },
    
      onGotUserInfo:function(){
        var that = this;
        wx.getSetting({
          success: function (res) {
            console.log("授权结果成功:" + res)
            if (res.authSetting['scope.userInfo']) {
              // 已经授权,可以直接调用 getUserInfo 获取头像昵称
              wx.getUserInfo({
                lang:"zh_CN",
                withCredentials: true,
                success: function (res) {
                  app.globalData.g_userInfo = res.userInfo;
                  // //将用户的基本信息保存到缓存中
                  wx.setStorageSync("user", res.userInfo);
                  console.log("用户基本信息获取成功:" + res.userInfo)
                },
                fail: function (res) {
                  console.log("用户基本信息获取失败:" + res)
                }
              })
            }
            that.jumpToPostPage();
          },
          fail: function () {
            console.log("授权结果失败:" + res)
          }
        })
        
      },
    
      getUserInfo: function () {
        var userInfoStorage = wx.getStorageSync("user");
        if (!userInfoStorage) {
          console.log("缓存中没有用户基本信息")
          //如果缓存中没有用户信息,那么获取用户信息
          var that = this;
          wx.login({
            success: function (res) {
              console.log("登录成功:" + res.code);
              that.setData({
                loginCode: res.code
              })
            }
          })
        } else {
          //如果缓存中已经有用户信息,那么将用户信息保存到全局变量中
          console.log("缓存中已经有用户基本信息")
          app.globalData.g_userInfo = userInfoStorage;
        }
      },
    
      //跳转到post列表页面
      jumpToPostPage:function(){
        wx.switchTab({
    
          url: '../post/post',
    
          success: function () {
            console.log("跳转页面成功")
          },
    
          fail: function () {
            console.log("跳转页面失败")
          },
    
          complete: function () {
            console.log("跳转页面完成")
          },
        });
      },
    
      /**
       * 生命周期函数--监听页面加载
       */
      onLoad: function (options) {
        this.getUserInfo();
      },
    
      /**
       * 生命周期函数--监听页面初次渲染完成
       */
      onReady: function () {
        
      },
    
      /**
       * 生命周期函数--监听页面显示
       */
      onShow: function () {
        
      },
    
      /**
       * 生命周期函数--监听页面隐藏
       */
      onHide: function () {
        console.log("欢迎页面被隐藏")
      },
    
      /**
       * 生命周期函数--监听页面卸载
       */
      onUnload: function () {
        console.log("欢迎页面被卸载")
      },
    
      /**
       * 页面相关事件处理函数--监听用户下拉动作
       */
      onPullDownRefresh: function () {
        
      },
    
      /**
       * 页面上拉触底事件的处理函数
       */
      onReachBottom: function () {
        
      },
    
      /**
       * 用户点击右上角分享
       */
      onShareAppMessage: function () {
        
      }
    })
    
    image.png

    2.3 获取用户信息并绑定

    setting.js
    image.png image.png image.png

    3、数据缓存的异步操作

    使用异步的清除缓存方法: wx.clearStorage

    3.1 showModal公共方法

    setting.js
    //显示模态窗口
      showModal:function(title,content,callback){
        wx.showModal({
          title: title,
          content: content,
          confirmColor:"#1F4BA5",
          cancelColor:"#7FB389",
          success:function(res){
            if (res.confirm){
              // callback;
              callback && callback();
            }
          }
        })
      },
    
      //缓存清理
      clearCache:function(){
        this.showModal("缓存清理","确定要清除本地缓存吗?",function(){
          wx.clearStorage({
            success:function(msg){
              wx.showToast({
                title: '缓存清理成功',
                duration:1000,
                mask:true,
                icon:"success"
              })
            },
            fail:function(e){
              console.log(e)
            }
          });
        })
      }
    
    image.png image.png

    4、获取系统信息

    4.1 新增device页面

    app.json
    image.png

    4.2 showDeviceInfo函数

    setting.js
    image.png

    4.3 device子页面的骨架

    device.wxml
    <view class="container">
      <view class="category-item personal-info">
        <view class="user-avatar">
          <image src="{{userInfo.avatarUrl}}"></image>
        </view>
        <view class="user-name">
          <view class="user-nickname">
            <text>{{userInfo.nickName}}</text>
          </view>
          <view class="user-locaiton">
            <text>所在地:{{userInfo.city}}</text>
          </view>
        </view>
      </view>
      <view class="category-item">
        <block wx:for="{{cache}}">
          <view class="detail-item" catchtap="{{item.tap}}">
            <image src="{{item.iconurl}}"></image>
            <text>{{item.title}}</text>
            <view class="detail-item-btn"></view>
          </view>
        </block>
      </view>
      <view class="category-item">
        <block wx:for="{{device}}">
          <view class="detail-item" catchtap="{{item.tap}}">
            <image src="{{item.iconurl}}"></image>
            <text>{{item.title}}</text>
            <view class="detail-item-btn"></view>
          </view>
        </block>
      </view>
      <view class="category-item">
        <block wx:for="{{api}}">
          <view class="detail-item" catchtap="{{item.tap}}">
            <image src="{{item.iconurl}}"></image>
            <text>{{item.title}}</text>
            <view class="detail-item-btn"></view>
          </view>
        </block>
      </view>
      <view class="category-item">
        <block wx:for="{{others}}">
          <view class="detail-item" catchtap="{{item.tap}}">
            <image src="{{item.iconurl}}"></image>
            <text>{{item.title}}</text>
            <view class="detail-item-btn"></view>
          </view>
        </block>
      </view>
    
    </view>
    
    

    4.4 device子页面的样式

    device.wxss
    .container {
        background-color: #efeff4;
        width: 100%;
        height: 100%;
        flex-direction: column;
        display: flex;
        align-items: center;
        min-height: 100vh;
    }
    .category-item {
        width: 100%;
        margin: 20rpx 0;
        border-top: 1rpx solid #d9d9d9;
        border-bottom: 1rpx solid #d9d9d9;
        background-color: #fff;
    }
    .detail-item{
        display: flex;
        margin-left: 30rpx;
        border-bottom: 1px solid RGBA(217, 217, 217, .4);
        height:85rpx;
        align-items: center;
    }
    .detail-item:last-child{
        border-bottom:none;
    }
    .detail-item text{
        color:#7F8389;
        font-size:24rpx;
        flex:1;
    }
    .detail-item text:last-child{
        color:#7F8389;
        font-size:24rpx;
        flex:1;
        text-align: right;
        padding-right: 20rpx;
    }
    

    4.5 获取系统信息

    device.js
    Page({
      data: {
        phoneInfo: [],
        softInfo: [],
        screenInfo: [],
      },
      onLoad: function () {
        var that = this;
        wx.getSystemInfo({
          success: function (res) {
            console.log(res)
            that.setData({
              phoneInfo: [
                { key: "手机型号", val: res.model },
                { key: "手机语言", val: res.language }
              ],
              softInfo: [
                { key: "微信版本", val: res.version },
                { key: "操作系统版本", val: res.system },
                { key: "客户端平台", val: res.platform }
              ],
              screenInfo: [
                { key: "屏幕像素比", val: res.pixelRatio },
                { key: "屏幕尺寸", val: res.windowWidth + '×' + res.windowHeight }
              ]
            });
          }
        });
    
        wx.setNavigationBarTitle({
          title: '系统信息',
        })
      }
    });
    
    image.png

    5、获取网络状态

    image.png image.png

    5.1 获取网络状态信息

    setting.js
    image.png image.png

    6、获取当前位置信息和当前速度信息

    image.png
    image.png

    6.1 获取当前位置和速度信息

    setting.js
      //获取当前位置经纬度和当前速度
      getLonLat:function(callback){
        var that = this;
        wx.getLocation({
          type: "gcj02",
          success: function(res) {
            callback(res.longitude,res.latitude,res.speed);
          },
        })
      },
    

    6.2 显示当前位置和速度信息

    setting.js
     showLonLat:function(){
        var that = this;
        this.getLonLat(function(lon,lat,speed){
          console.log("lon=========" + lon);
          console.log("lat=========" + lat);
          var lonStr = lon >= 0 ? '东经' : '西经',
            latStr = lat >= 0 ? '北纬' : '南纬';
    
            //保留2位小数
          lon = lon.toFixed(2);
          lat = lat.toFixed(2);
          console.log("lon.toFixed(2)=========" + lon);
          console.log("lat.toFixed(2)=========" + lat);
          lonStr += lon;
          latStr += lat;
          speed = (speed || 0).toFixed(2);
          that.showModal('当前位置和速度', '当前位置:' + lonStr + ',' + latStr + '。速度:' + speed + 'm/s');
        });
      }
    
    image.png
    image.png

    7、使用微信内置地图查看位置信息

    image.png image.png

    7.1 在地图上显示坐标点

    setting.js
    //在地图上显示坐标点
      showMap:function(){
        this.getLonLat(function(lon,lat){
          wx.openLocation({
            latitude: lat,
            longitude: lon,
            scale:15,
            name:"荔枝楼",
            address:"中山大道车陂路口高地大街76号高地大厦2楼",
            fail:function(){
              wx.showToast({
                title: '地图打开失败',
                duration:100,
                icon:"cancel"
              })
            }
          })
        });
      }
    
    image.png

    8、监听罗盘数据制作一个简易指南针

    image.png
    image.png
    image.png
    image.png

    8.1 在地图上显示坐标点

    setting.wxml
    image.png

    8.2 初始化变量值

    setting.js
    image.png

    8.3 显示罗盘

    setting.js
    
      //显示罗盘
      showCompass:function(){
        var that = this;
        this.setData({
          compassHidden:false
        })
        wx.onCompassChange(function(res){
          if(!that.data.compassHidden){
            this.setData({
              compassVal:res.direction.toFixed(2)
            })
          }
        })
      },
    
    

    8.4 隐藏罗盘

    setting.js
     //隐藏罗盘
      hideCompass:function(){
        this.setData({
          compassHidden:true
        })
      }
    
    image.png

    9、在小程序中实现摇一摇

    image.png

    9.1 添加摇一摇计数面板

    setting.wxml
    image.png

    9.2 添加shakeInfo和shakeData变量

    setting.js
    image.png

    9.3 摇一摇具体实现

    setting.js
     //摇一摇
      shake: function () {
        var that = this;
        //启用摇一摇
        this.gravityModalConfirm(true);
    
        wx.onAccelerometerChange(function (res) {
          //摇一摇核心代码,判断手机晃动幅度
          var x = res.x.toFixed(4),
            y = res.y.toFixed(4),
            z = res.z.toFixed(4);
          var flagX = that.getDelFlag(x, that.data.shakeData.x),
            flagY = that.getDelFlag(y, that.data.shakeData.y),
            flagZ = that.getDelFlag(z, that.data.shakeData.z);
    
          that.data.shakeData = {
            x: res.x.toFixed(4),
            y: res.y.toFixed(4),
            z: res.z.toFixed(4)
          };
          if (flagX && flagY || flagX && flagZ || flagY && flagZ) {
            // 如果摇一摇幅度足够大,则认为摇一摇成功
            if (that.data.shakeInfo.enabled) {
              that.data.shakeInfo.enabled = false;
              that.playShakeAudio();
            }
          }
        });
      },
    

    9.4 开启或关闭摇一摇

    setting.js
    //启用或者停用摇一摇功能
      gravityModalConfirm: function (flag) {
        if (flag !== true) {
          flag = false;
        }
        var that = this;
        this.setData({
          shakeInfo: {
            gravityModalHidden: !that.data.shakeInfo.gravityModalHidden,
            num: 0,
            enabled: flag
          }
        })
      },
    

    9.5 计算偏移量

    setting.js
      //计算摇一摇的偏移量
      getDelFlag: function (val1, val2) {
        return (Math.abs(val1 - val2) >= 1);
      },
    

    9.6 摇一摇成功后播放声音

    setting.js
     // 摇一摇成功后播放声音并累加摇一摇次数
      playShakeAudio: function () {
        var that = this;
        wx.playBackgroundAudio({
          dataUrl: 'http://7xqnxu.com1.z0.glb.clouddn.com/wx_app_shake.mp3',
          title: '',
          coverImgUrl: ''
        });
        wx.onBackgroundAudioStop(function () {
          that.data.shakeInfo.num++;
          that.setData({
            shakeInfo: {
              num: that.data.shakeInfo.num,
              enabled: true,
              gravityModalHidden: false
            }
          });
        });
      },
    

    10、扫码

    image.png
    image.png

    10.1实现扫码功能

    setting.js
     //实现扫码功能
      scanQRCode:function(){
        var that = this;
        wx.scanCode({
          success:function(res){
            console.log(res);
            that.showModal("扫描二维码/条形码",res.result,false);
          },
          fail:function(res){
            that.showModal("扫描二维码/条形码", "扫描失败,请重试!", false);
          }
        })
      }
    

    11、获取小程序页面二维码

    1)HTTP类型为POST
    2)接收的参数:path 、width(默认430)
    3)调用接口前要先获取access_token
    获取方法:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183

    12、下载并预览pdf、word等多种类型文档

    12.1 新增download页面

    app.json
    image.png

    12.2 跳转到download页面

    setting.js
    image.png

    12.3 download页面的骨架代码

    dowmload.wxml
    <view class="container">
      <view class="file-type-head">
        <text>文件类型</text>
      </view>
      <view class="category-item">
        <block wx:for="{{fileTypeList}}">
          <view class="detail-item" catchtap="downloadFile" data-type="{{item.type}}">
            <image src="{{item.iconurl}}"></image>
            <text>{{item.title}}</text>
            <view class="detail-item-btn"></view>
          </view>
        </block>
      </view>
    </view>
    
    

    12.4 download页面的样式代码

    dowmload.wxss
    .file-type-head {
      display: flex;
      align-items: center;
      height: 70rpx;
      width: 100%;
      text-indent: 30rpx;
    }
    
    .file-type-head text {
      font-size: 32rpx;
    }
    
    .category-item {
      margin-top: 0;
    }
    
    .container {
      background-color: #efeff4;
      width: 100%;
      height: 100%;
      flex-direction: column;
      display: flex;
      align-items: center;
      min-height: 100vh;
    }
    
    .category-item {
      width: 100%;
      margin: 20rpx 0;
      border-top: 1rpx solid #d9d9d9;
      border-bottom: 1rpx solid #d9d9d9;
      background-color: #fff;
    }
    
    .category-item.personal-info {
      height: 130rpx;
      display: flex;
      padding: 20rpx 0;
    }
    
    .category-item.personal-info .user-avatar {
      margin: 0 30rpx;
      width: 130rpx;
      height: 130rpx;
      position: relative;
    }
    
    .category-item.personal-info .user-avatar image {
      vertical-align: top;
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      border-radius: 2rpx;
    }
    
    .category-item.personal-info .user-name {
      margin-right: 30rpx;
      flex: 1;
      padding-top: 10rpx;
    }
    
    .detail-item {
      display: flex;
      margin-left: 30rpx;
      border-bottom: 1px solid RGBA(217, 217, 217, 0.4);
      height: 85rpx;
      align-items: center;
    }
    
    .detail-item:last-child {
      border-bottom: none;
    }
    
    .detail-item image {
      height: 40rpx;
      width: 40rpx;
    }
    
    .detail-item text {
      color: #7f8389;
      font-size: 24rpx;
      flex: 1;
      margin-left: 30rpx;
    }
    
    .detail-item .detail-item-btn {
      width: 50rpx;
      color: #d9d9d9;
      height: 40rpx;
      margin-right: 20rpx;
      /*background-color: red;*/
      text-align: center;
    }
    
    .detail-item .detail-item-btn::after {
      display: inline-block;
      content: '';
      width: 16rpx;
      height: 16rpx;
      color: #d9d9d9;
      margin-top: 8rpx;
      border: 3rpx #d9d9d9 solid;
      border-top-color: transparent;
      border-left-color: transparent;
      transform: rotate(-45deg);
    }
    
    

    12.5 download页面的样式代码

    dowmload.js
    image.png

    12.6 下载并且预览文档

    dowmload.js
    downloadFile: function (event) {
        var type = event.currentTarget.dataset.type,
          url = 'https://coding.net/u/airbreak/p/wx_app_files/git/raw/master/top10.';
        switch (type) {
          case "pdf":
            url += 'pdf';
            break;
          case "word":
            url += 'docx';
            break;
          case "excel":
            url += 'xlsx';
            break;
          default:
            url += 'pptx';
            break;
        }
        wx.downloadFile({
          url: url,
          success: function (res) {
            var filePath = res.tempFilePath;
            console.log(filePath);
            wx.openDocument({
              filePath: filePath,
              success: function (res) {
                console.log('打开文档成功')
              },
              fail: function (res) {
                console.log(res)
              }, complete: function (res) {
                console.log(res);
              }
            })
          },
          fail: function () {
            console.log('下载失败');
          }
        })
      },
    
    image.png
    image.png image.png

    相关文章

      网友评论

        本文标题:1.10 设置

        本文链接:https://www.haomeiwen.com/subject/qasuyftx.html