关于uniapp开发微信小程序的项目技巧(一)

3,140 阅读2分钟
  • v-cloak
    指令设置样式,解决由于网络加载慢,在页面上会显示源码闪动问题,当编译结束,会自动移除

  • 箭头函数
    function (x) {return x * x}, x => x * x

  • 封装消息提示框

    Vue.prototype.$showToast=function(mes){
	if(mes&&typeof mes=='string'){
		uni.showToast({
			title: mes,
			icon:'none',
			duration: 2000
		})
	}
}
this.$showToast('你没有权限')
  • 管道符过滤器处理浮点数小数位

    main.js引入

    import filters from "./components/filter.js"
    

    根目录components创建代码

    let toFixed=(input,num)=>Number(input).toFixed(num)
    
    export default {toFixed}
    

    页面中应用

    <view class="num" v-cloak><span>¥</span>{{tradeData.jrje|toFixed(2)}}</view>
    

    注意:toFixed(),可把 Number 四舍五入为指定小数位数的数字

  • computed
    计算属性监控Store里state定义变量,实现双向数据绑定 mapState()是辅助函数,获取的是state里的值,这样可以直接获取多个变量值,就不需要使用this.$state.sessionKey引用

    computed: mapState(['sessionKey','merchantList','userId','hadAuthorize'])
    
  • uni.on(eventName,callback)
    监听全局的自定义事件。事件可以由 uni.$emit 触发,回调函数会接收所有传入事件触发函数的额外参数。

    uni.$on('changeMerchantIndex',()=>{
        this.setUserIdByStorage()
    })

    switchStore(index){	
        uni.$emit('changeMerchantIndex',index);
    }
  • uni.setStorageSync(KEY,DATA)
    将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口
    A页面
    saveA() {
        uni.setStorageSync('merchantIndex',index)
    }
    B页面
    let get = uni.getStorageSync('merchantIndex')
  • mapMutations
    ...mapMutations(['A'])  ||  ...mapMutations({'A': 'A' })
    mapMutations会将 this.A 映射成 this.$store.commit('A') 
  • mapState
   ...mapMutations(['A'])  ||  ...mapMutations({'A': 'A' })
  mapMutations会将 this.A 映射成 this.$store.$state('A') 
  • uni.scanCode 扫描二维码
   uni.scanCode({
	success: (res) => {
	    this.codeResult = res.result
	}
})
  • uni.getLocation 获取定位
   goPosition() {
	// 授权用户开启地理位置信息,如之前已经授权,则不会弹出弹框
	uni.authorize({
	    scope: 'scope.userLocation',
	    success: (res) => {
                console.log(res)
	        uni.getLocation()
	    }
	})
	// 获取当前的地理位置
	    uni.getLocation({
	        success: (res) =>{
		    // 定位权限开启,打开地图
	            // uni.chooseLocation()
		    // 获取具体位置信息
		    this.latitude = res.latitude // 纬度
		    this.longitude = res.longitude // 精度
		    uni.navigateTo({
		        url:'./scenicSpot/scenicSpot'
		    })
		},
		fail(e) {
		    // 定位权限未开启,引导设置
		    uni.showModal({
	       	        title: '地理位置未授权',
			content: '如需使用柚客,请开启您手机中的定位授权,开启后重新打开小程序',
			confirmText: '去授权',
			success(res){
			    if (res.confirm) {
			        //打开授权设置,访问我的位置和用户信息
				uni.openSetting({
			            success(res) {
                                        console.log(res)
				    }
			        })
			        },
			    }
			}
		    })
	        }
            })	
			
  • uni.navigateTo()
    保留当前页面,跳转到应用内的某个页面,使用uni.navigateBack可以返回到原页面。
   goStatistics() {
        uni.navigateTo({
	    url:'./consumeStatistics/consumeStatistics'
        })
    },