uni-app 学习笔记

328 阅读4分钟

什么是uni-app?

uni-app 是一个使用 Vue.js 开发所有前端应用的框架,开发者编写一套代码,可发布到iOS、Android、H5、以及各种小程序(微信/支付宝/百度/头条/QQ/钉钉)等多个平台。

uni-app特点

1、跨平台

一套代码多端发行,而不失优雅(条件编译,保留不同平台独有特色功能方法调用)

条件编译

#ifdef %PLATFORM% //这些代码只在该平台编译 #endif

#ifdef : if defined 仅在某个平台编译 #ifndef : if not defined 在除里该平台的其他编译 #endif : end if 结束条件编译 %PLATFORM% 需要编译的平台,上面的MP就是各个小程序的意思

常用 %PLATFORM% h5 h5平台 MP-WEIXIN 微信小程序 MP-ALIPAY 支付宝小程序 MP-BAIDU 百度小城 MP-TOUTIAO 头条小程序

2、通用技术栈,学习成本低

Vue的语法,微信小程序Api,内嵌mpvue可以直接迁移,如果你会Vue可以直接入门

3、生态丰富

支持npm下载第三方模块,支持小程序自定义组件,SDK,兼容mpvue组件,支持原生混合编码

常用基本操作

1、节点操作 微信小程序里面没有 window,document对象,那如果需要进行dom操作

var query=uni.createSelectorQuery();
​
query.select(".titlerh").boundingClientRect((nodes)=>{
    console.log(nodes)
}).exec();
​
query.select(".box1")
    .boundingClientRect()
    .selectAll(".box2")
    .boundingClientRect()
    .exec((res)=>{
      console.log(res);
});

2、生命周期 应用生命周期 App.vue

App({
  onLaunch (options) {
      console.log("小程序初始化");
  },
  onShow (options) 
      console.log("小程序显示");
  },
  onHide () {
      console.log("小程序隐藏");
  }
})

分页生命周期 pages

Page({
  onLoad: function(options) {
    // 页面创建时执行
      console.log("页面加载");
  },
  onShow: function() {
    console.log("页面进入");
  },
  onReady: function() {
    console.log("页面首次渲染完毕时执行");
  },
  onHide: function() {
    console.log("页面离开");
  },
  onPullDownRefresh: function() {
    // 触发下拉刷新时执行
    console.log("下拉触发");
    //enablePullDownRefresh 开启下拉  
  },
  onReachBottom: function() {
    // 页面触底时执行
    console.log("下拉到底");  
  },
  onShareAppMessage: function (e) {
      // 页面被用户分享时执行
      //通过按钮调用
      
      //点击触发弹窗
      <button open-type="share">分享</button>  
      console.log("用户分享");  
      return {
          title: '图片',
          path: '/pages/index/index', //当前页面 path
          imageUrl: "/images/1.jpg",
          desc: '开发',
          success: (res) => {
              console.log("转发成功", res);
          },
          fail: (res) => {
              console.log("转发失败", res);
          }
      }
  },
  onPageScroll: function() {
    console.log("页面滚动时执行");
  },
 onResize: function() {
    console.log("屏幕旋转触发");
  }
})
组件生命周期

uni-app components组件支持的生命周期,与vue标准组件的生命周期相同。wx小程序支持生命周期

beforeCreate(){} // 在实例初始化之后被调用
created(){} // 在实例创建完成后被立即调用。
beforeMount(){} // 在挂载开始之前被调用。
mounted(){} // 挂载到实例上去之后调用。
beforeDestroy(){} // 实例销毁之前调用。在这一步,实例仍然完全可用。

3、常用API调用

获取用户授权弹窗

<button open-type="getUserInfo" @getuserinfo="eventName"> 获取头像昵称 </button>
getUserInfo: function(e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
        userInfo: e.detail.userInfo,
        hasUserInfo: true
    })
}

返回所有用户授权

wx.getSetting({success:()=>{"返回用户所有用户授权"}})

照相机接口

因为,调用照相机获取临时图片格式,直接上传三方服务器,是不支持的,需要微信做解析,转发

wx.uploadFile 上传微信需要做转发看不到传输的参数

uni.chooseImage({
    count: 1, //图片张数
    sizeType: ['original', 'compressed'],//原图,压缩图,
    sourceType: ['album', 'camera'],  //本地相册,拍照
    success :res=> {
        const tempFilePaths = res.tempFilePaths//微信小程序图片临时路径
        this.setData({tempFilePaths}); 
    },
    fail: err=>{
    }
})
uni.chooseVideo({
    count: 1, //视频个数
    mediaType: ['image', 'video'],//文件类型,
    sourceType: ['album', 'camera'],  //本地相册,拍摄
    camera: 'front',   //仅在 sourceType 为 camera 时生效,使用前置或后置摄像头,'front'、'back',默认'back'
    success :res=> {
        const tempFilePaths = res.tempFilePaths//微信小程序图片临时路径
        this.setData({tempFilePaths}); 
    },
    fail: err=>{
    }
})

// 预览接口
viewImgs(index) {
    uni.previewImage({
        current: this.data.tempFilePaths[index], // 当前显示图片的http链接
        urls:this.data.tempFilePaths // 需要预览的图片http链接列表
    });
},
    
//图片上传    
fileUplaod() {
    uni.uploadFile({
      url: "",
      filePath: this.data.tempFilePaths[0],
      name: "file", //上传图片key
      formData: {
        user: "MSea" //需要额外携带参数
      },
      header: {
        "content-type": "multipart/form-data"
      },
      success: res => {
        console.log("data");
      }
    });
  }
请求

微信原生请求接口

注意设置,不效验合法域名,回忆怎么添加合法域名

//GET 会自动拼接参数
//queryStringParams
uni.request({
    method: "GET",
    url: "https://cnodejs.org/api/v1/topics",
    data: { 
        uname: "Msea"
    },
    success: (res) => {
        console.log(res)
    }
})
//POST 默认参数为payLoad,为json
uni.request({
    method: "POST",
    url: "https://cnodejs.org/api/v1/topics",
    data: { 
        uname: "Msea" 
    },
    success: (res) => {
        console.log(res)
    }
})
//POST form-data 数据 
// 'content-type': 'multipart/form-data'  用于文件上传  
uni.request({
   url: 'https://cnodejs.org/api/v1/topic/5433d5e4e737cbe96dcef312',
    data:{fileId:'123'},
    method:'POST',
    header: {
        'content-type': 'application/x-www-form-urlencoded'
    },
    success:function(res){}
})
键盘

隐藏软键盘

uni.hideKeyboard()

地图组件

<map 
    id="map" 
    longitude="经度" 
    latitude="纬度" 
    scale="缩放级别(14)" 
    bindcontroltap="点击地图触发FN" 
    markers="{{添加标记}}" 
    bindtap="markertap" 点解地图触发
    show-location  将地图中心移置当前定位点,此时需设置地图组件 show-location 为true。
    style="width: 100%; height: 300px;"></map>

移动地图中心点

移动端测试有效

onShow: function() { // 地图上下文对象 this.mapCtx = uni.createMapContext('map'); },

  ckMap(e){
      //小程序不支持 Objcet.assign
      var temp={
          iconPath: "/assets/img/local.png",
          id: 0,
          width: 25,
          height: 25,
          ...e.detail
      }
      var markers=this.data.markers;
      markers.push(temp);
      this.setData({markers},()=>{
          var data={
              ...e.detail
          };
          this.mapCtx.moveToLocation(data)
      })
  } 
定位
uni.getLocation({
    type: 'gcj02', //腾讯地图坐标系
    success:(res)=> {
        const latitude = res.latitude
        const longitude = res.longitude
        }
})  

用户授权弹窗

app.json配置文件

//app.json
{
  "pages": ["pages/index/index"],
  "permission": {
    "scope.userLocation": {
      "desc": "需要获取您的位置" // 高速公路行驶持续后台定位
    }
  }
}
获取当前位置并移动地图中心店
wx.getLocation({
    type: 'gcj02', //腾讯地图坐标系
    success: (res) => {
        const latitude = res.latitude
        const longitude = res.longitude
        var temp = {
            iconPath: "/assets/img/local.png",
            id: 0,
            width: 25,
            height: 25,
            latitude,
            longitude
        }
        var markers = this.data.markers;
        markers.push(temp);
        this.setData({
            markers
        }, () => {
            var data = {
                latitude,
                longitude
            };
            this.mapCtx.moveToLocation(data)
        })
    }
})