uni项目中,常用知识汇总

655 阅读2分钟

页面跳转

  1. uni.navigateTo
  // url通过字符串拼接的方式传递,这样再h5端,页面刷新,数据不会丢失
  // url最前面要`/`
  uni.navigateTo({
    url: '/pages/home/home?age=22&city=成都',
    success({res}) {
      // 跳转成功的方法,这里一般处理向跳转的页面传递参数,数据大的参数,小的参数通过url拼接
      const { eventChannel } = res
      eventChannel.emit('setHomeToData', {name: '蔡博', age: 22, sex: '男'})
    }
  })

  // home接受数据
  //1. 通过url拼接接收参数
  onLoad(data) {
    console.log('上个页面传来的数据', data)
  }

  /* 通过eventChannel传递数据 */
  onLoad(data) {
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('setHomeToData', (res) => {
      // 获取通过eventChannel传来的数据,相当于eventbus
      // 由于跳转页面还没生成,使用直接用eventBus不会触发
      console.log('数据', res)
    })
  }

  1. uni.redirectTo() uni.reLaunch() uni.navigateBack()

redirectTo 关闭当前页,打开新页面 reLaunch 关闭所有页,打开新页面 navigateBack 返回页面 关闭所有页面跳转用相对路径跳转才生效uni.reLaunch({url: '../../Main/LookTalent/LookTalent'})

向返回的页面传递数据,一般通过eventBus

  // 返回的页面接受数据
  created() {
    uni.$on('getHomeToData', this.getHomeToData)
  },
  beforeDestroy() {
    uni.$off('getHomeToData', this.getHomeToData)
  },
  methods: {
    getHomeToData(data) {
      console.log('about测试', data)
    }
  }
  /* 一般都在created-beforeDestroy生命周期触发和销毁自定义事件*/
  // 点击返回按钮触发
  goBack() {
    // 设置数据
    uni.$emit('getHomeToData', {x: 66})
    uni.navigateBack()
  }
  1. navigateToMiniProgram 打开新的小程序
uni.navigateToMiniProgram({
  appId: '' //传入小程序的appId
})

常用弹窗

  1. uni.showToast()
  // 一般提示不显示icon,直接显示title
  // icon:取值success,error,loading
  uni.showToast({
    title: '成功',
    icon: 'none'
  })
  1. uni.showLoading()
  wx.showLoading({
    title: '加载中',
  })

  setTimeout(function () {
    // 请求结束后,需调用hideLoading隐藏
    wx.hideLoading()
  }, 2000)
  1. showModal
  // showCancel是否显示取消按钮
  // cancelText取消按钮的文字
  // cancelColor取消按钮的文字颜
  // confirmText确认按钮的文
  // confirmColor确认按钮颜色
  // editable是否显示输入框
  // placeholderText 输入框默认文字

  wx.showModal({
    title: '提示',
    content: '这是一个模态弹窗',
    success (res) {
      console.log('res', res)
      if (res.confirm) {
        console.log('用户点击确定')
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    }
  })
  1. showActionSheet 操作上拉
  wx.showActionSheet({
    itemList: ['A', 'B', 'C'],
    success (res) {
      // 获取下标
      console.log(res.tapIndex)
    },
    fail (res) {
      console.log(res.errMsg)
    }
  })
  1. 打电话makePhoneCall
  uni.makePhoneCall({
    phoneNumber: 15888888888
  });

获取元素高度

// https://uniapp.dcloud.io/api/ui/nodes-info
uni.getSystemInfo({
  success: function (res) { // res - 各种参数

    let obj = uni.createSelectorQuery().select('.类名')

    obj.boundingClientRect(function (data) { // data - 各种参数
      
      console.log(data)

    }).exec()
  }
})

微信授权手机号登录

  <button type="default" class="t-btn" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">微信号快速登录</button>
  <!-- 设置open-type="getPhoneNumber" -->
  <!-- 触发getphonenumber方法 -->
// 登录流程
// 先通过uni.login获取js-code请求接口传给后端,后端返回openId
// 通过openId去获取token,然后每个接口加上token信息
  uni.login({
    success: async (data) => {
      resolve(data.code)
    },
    fail: (err) => {
      console.log('uni.login 接口调用失败,将无法正常使用开放接口等服务', err)
      reject(err)
    }
  })

获取定位和地址逆解析

  _getLocation() {
    // 定位当前位置
    const txMapKey = null //腾讯地图的key,生产环境,公司会提供
    return new Promise((resolve, reject) => {
      uni.getLocation({
        type: 'wgs84',
        success: async (res) => {
          const { latitude, longitude } = res
          // 地址逆解析
          const resData = await uni.$u.http.get(`https://apis.map.qq.com/ws/geocoder/v1/?key=${txMapKey}&location=${latitude},${longitude}`)
          if(!resData.result) {
            return
          }
          const ad_info = resData.result.ad_info
          const cityData = {
            city: ad_info.city,
            cityId: ad_info.adcode
          }
          this.$store.commit('SET_LOCATIONCITY', cityData)
          resolve(cityData)
        },
        fail(res) {
          reject(res)
        }
      })
    })
  }

  // 实时位置更新一般使用onLocationChange
  const _locationChangeFn = function(res) {
    console.log('location change', res)
  }
  uni.onLocationChange(_locationChangeFn)

  // 打开地图预览
  uni.openLocation({
    latitude,
    longitude,
    scale: 18
  })

设置地图经纬度

https://developers.weixin.qq.com/miniprogram/dev/api/media/map/MapContext.html
// MapContext.moveToLocation(Object object)
// 将地图中心移置当前定位点,此时需设置地图组件 show-location 为true。2.8.0 起支持将地图中心移动到指定位置
<map />//组件
// 实时更新地图的定位坐标
MapContext.moveToLocation({
  longitude: "",
  latitude: "",
  success() {

  }
})

图片,视频预览,下载


  // 下载图片,保存图片的到相册
  wx.saveImageToPhotosAlbum({
    filePath: ''
  })
  // 图片预览,不再更新,现在用过下面这个`previewMedia`
  uni.previewImage({
    urls: this.getUrls,
    current: '', //当前显示图片的链接
  })
  // 预览图片和视频
  wx.previewMedia({
    sources: [{
      url: '',//路径
      type: '', //image-video图片或者视频
      poster: ''//视频的封面
    }],
    current: 0//当前预览的位置下标
  })
  https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.previewMedia.html

上传chooseMedia

  // 上传图片
  uni.chooseImage()
  // 上传视频
  uni.chooseVideo()
  
  // 上面的不再更新
  wx.chooseMedia({
    count: 1, //数量mediaType
    mediaType: [],
    success(res) {
      
    }
  })

自定义常用picker组件

<template>
  <picker @change="bindPickerChange" :value="[index]" :range="listName" mode="selector">
    <slot v-if="selectName"></slot>
    <view v-else>请选择</view>
  </picker>
</template>

<script>
  //  子组件
export default {
    props: {
      value: {
        type: [Number, String],
        default: 0
      },
      selectName: {
        type: [Number, String],
        default: ''
      },
      list: {
        type: Array,
        default: []
      }
    },
    data() {
        return {

        }
    },
    computed: {
      listName() {
        return this.list.map(item => item.name)
      },
      index() {
        return this.list.findIndex(item => item.id === this.value) || 0
      }
    },
    methods: {
        bindPickerChange(e) {
            const index = e.target.value
            const data = this.list[index]
            this.$emit('input', data.id)
            this.$emit('update:selectName', data.name)
        }
    }
}
</script>


<template>
    <view>
        <at-picker v-model="selectVal" :selectName.sync="selectName" :list="array">
            <view>{{selectName}}</view>
        </at-picker>
    </view>
</template>

<script>
// 父组件
export default {
    data() {
        return {
            selectVal: 2,
            selectName: '',
            array: [{
                id: 88,
                name: '成都'
            }, {
                id: 22,
                name: '北京'
            }, {
                id: 66,
                name: '重庆'
            }]
        }
    },
    onLoad(data) {
        // console.log('列表', data)
    },
    watch: {
        selectVal(val) {
            console.log('valk', val)
        }
    },
    methods: {
        bindPickerChange(e) {
            // console.log('e', e)
            this.index = e.target.value
        }
    }
}
</script>

小程序登录

  1. developers.weixin.qq.com/miniprogram…
  2. developers.weixin.qq.com/miniprogram…