uniapp常用api

CSS

按网上教程 css

常用api

tabbar pages.json

下拉刷新

基础 console.log (clog) 调试断点

定时器

生命周期 应用级 APP.vue 页面级 组件级

页面级

<template>
	<view>
		<view style="height: 2000rpx;background-color: #4CD964;"></view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				msg:"sduuuu",
				num:60
			}
		},
		methods: {

		},
		onLoad() {
			console.log("onload");
			uni.startPullDownRefresh({
				complete() {
				}
			})
		},
		onShow() {
			console.log("onshow");
		},
		onReady() {
			console.log("onready");
		},
		onHide() {
			console.log("onhide");
		},
		onUnload() {
			console.log("onunload");
		},
		onPullDownRefresh() {
			console.log("下拉刷新");
			let timer = setTimeout(()=>{
				uni.stopPullDownRefresh() //停止下拉刷新动作
				clearTimeout()  //记住清除计时器
			},3000) 
		},     //监听下拉刷新
		onReachBottom() {
			console.log("滚动到底部");   //到底部触发
		},
		onTabItemTap(res) {
			console.log("onTabItemTap : "+ JSON.stringify(res));  //底部导航栏触发 JSON.stringify 转化为json格式 在每个底部导航跳转页面都添加
		}
	}
</script>

onBackPress() {
			console.log('onbackpress');  //可以弹出一个窗口
		},   //页面跳转生命周期 返回页面调用

网络请求 uni.request

<button @click="apiclick">请求接口</button>
apiclick(){
				let url = 'http://route.showapi.com/341-2';
				//网络请求api
				uni.request({
					url:url,
					data:{},
					header:{},
					method:'GET',
					timeout:10000,
					dataType:'json',//默认json,
					success: (res) =>{
						console.log(res);
					},
					fail: (err) => {
						console.log(JSON.stringify(err));
					}
				})
			},

上传和下载 uni.upload uni.download

		<button @click="onuploadphoto">图片上传</button>
		<button @click="ondownload">下载</button>
		<image :src="downloadfile" style="width: 300rpx;height: 270rpx;" mode="aspectFill"></image>

		data() {
			return {
				downloadfile:''
			}
		},

		onuploadphoto(){
				uni.chooseImage({
					count:1,
					sizeType:[],
					sourceType:[],
					success: (res) => {
						console.log(JSON.stringify(res));
					},
					fail: () => {
						console.log(JSON.stringify(err));
					}
				})
			},
			ondownload(){
				uni.downloadFile({
					url:'https://img2.baidu.com/it/u=190271553,1135687029&fm=253&fmt=auto&app=138&f=JPEG?w=640&h=452',
					timeout:30000,
					success: (res) => {
						console.log(JSON.stringify(res));
						this.downloadfile = res.tempFilePath;    //显示图片
					},
					fail: (err)=>{
						console.log(JSON.stringify(err));
					}
				})
			}

路由和页面跳转

uni.navgateto

<button @click="onpagechange">页面跳转</button>

onpagechange(){
				uni.navigateTo({
					url:'../nav/nav?key1=value1@key2=value2',
					events:{
						onpageload:()=>{
							console.log('page loaded');   //定义一个事件  nav.vue发送一个事件
						}
					},
					success: () => {
						console.log('onpagechange');
					}
				})
			}

//nav.vue页面  onbackpress周期和onload设定
onLoad(option) {
//传递的参数
			let key1 = option.key1;  
			let key2 = option.key2;
			console.log(key1);
			console.log(key2);
			let timer = setTimeout(()=>{
				clearTimeout(timer);
			},3000);
			let loadtimer = setTimeout(()=>{
				const eventChannel = this.getOpenerEventChannel();
				eventChannel.emit('onpageload', {data: 'data from test page'});
				clearTimeout(loadtimer);
			},3000)
		},
		onBackPress() {
			console.log('onbackpress');  //可以弹出一个窗口
		}

uni.redirectto

//nav.vue页面
<button @click="onclosetoanother">关闭当前页面跳转</button>
onclosetoanother(){
				uni.redirectTo({
					url:'../page/page',   //注意index跳转好像不行
				})
			}

uni.relaunch 关闭所有页面打开某一页面

//page.vue 页面
<button @click="onrelaunch">关闭所有页面跳转</button>
onrelaunch(){
				uni.reLaunch({
					url:'../index/index'  //tab页面也可以跳转
				})
			}

uni.switchtab 跳转到tabbar页面,关闭所有非tabbar页面 同上

uni.navgateback 关闭当前页面返回上一页或多级页面

<button @click="onpageback">页面返回</button>
onpageback(){
				uni.navigateBack({
					delta:2 //返回页面数
				})
			}

uni.preloadpage 预加载

数据缓存 一般异步

用于登录时保存token数据

uni.setstorage 本地缓存 异步

<view @click="onsettimer">{{msg}}</view>

onLoad() {
			//取出本地缓存
			uni.getStorage({
				key:'msg',
				success: (res) => {
					console.log(res);
					let msg = res.data;
					this.msg = msg;
				}
			})
		},
		
onsettimer(){
				let timer = setTimeout(()=>{
					this.msg = "hey guy";
					//存入本地缓存
					uni.setStorage({
						key:'msg',
						data:this.msg,
						success: () => {
							console.log('setStorage succuess');
						}
					})
					clearTimeout(timer);
				},3000)
			},

uni.setstorgesync 本地缓存 同步

onLoad() {
			//同步取出缓存
			let res = uni.getStorageSync('msg');
			console.log(res);
			//取出本地缓存 异步
			uni.getStorage({
				key:'msg',
				success: (res) => {
					console.log(res);
					let msg = res.data;
					this.msg = msg;
				}
			})
		},

移除本地缓存

<button @click="onremovestorage">移除本地缓存</button>

onremovestorage(){
				//异步移除 
				uni.removeStorage({
					key:'msg',
					success: (res) => {
						console.log(res);
					}
				})
			},

移除所有本地缓存

<button @click="onclearstorage">清除本地所有缓存</button>

onclearstorage(){
				//异步清除
				uni.clearStorage({
					success:(res)=>{
						console.log(res);
					}
				})
			},

位置

uni.getLocation

<button @click="ongetlocation">获取位置信息</button>

ongetlocation(){
				uni.getLocation({
					geocode:true,
					success: (res) => {
						console.log(JSON.stringify(res.address));
					},
					fail: (err) => {
						console.log(err);
					}
				})
			}

uni.chooseLocation 打开地图选择位置

<button @click="onchooselocal">打开地图选择位置</button>

onchooselocal(){
				uni.chooseLocation({
					success: (res) => {
						console.log(JSON.stringify(res));
					}
				})
			}

uni.openLocation 使用应用内置地图查看位置

ongetlocation(){
				uni.getLocation({
					geocode:true,
					success: (res) => {
						console.log(JSON.stringify(res.address));
						let lat = res.latitude;  //获取纬度
						let lon = res.longitude;  //获取经度
						uni.openLocation({
							latitude:lat,
							longitude:lon,
							success: (re) => {
								console.log(re);
							}
						})
					},
					fail: (err) => {
						console.log(err);
					}
				})
			},

图片

<!-- 循环显示选中多张图片 -->
		<view style="display: flex;">
		<view v-for="(item,index) in picpaths" :key="index">
			<image :src="item" style="width: 300rpx;height: 400rpx;" mode="aspectFill"></image>
		</view>
		</view>
		<image :src="picpath" style="width: 300rpx;height: 250rpx;" mode="aspectFill"></image> <!-- 显示图片 -->

return {
				picpath:'',
				picpaths:[]
			}
	
onchooseimg(){
				let that = this;   //外部定义this
				uni.chooseImage({
					count:3,
					sizeType:[],
					success: (res) => {    //base6写法 不用外部定义this
						console.log(JSON.stringify(res));
						//回调显示图片
						that.picpath = res.tempFilePaths[0];
						that.picpaths = res.tempFilePaths;
						console.log(that.picpath);
					}
				})
			}

uni.previewImage 预览图片

<button @click="onpreimg">预览图片</button>

onpreimg(){
				uni.previewImage({
					loop:false,
					indicator:'default',
					count:this.picpre.length,   //存入图片列表长度
					current:'',
					urls:this.picpre,   //关键参数
					success: (res) => {
						console.log(JSON.stringify(res));
					},
					fail: (err) => {
						console.log(err);
					}
				})
			}

uni.getImageInfo 获取图片信息 长宽 用于瀑布流(耗性能,不推荐)

<!-- 动态显示图片,结合图片信息api -->
		<image :style="{width: imgwidth+'rpx',height: imgheight+'rpx'}" src="../../static/logo.png"></image>
		onLoad() {
			//页面加载获取本地图片
			uni.getImageInfo({
				src:'../../static/logo.png',
				success: (res) => {
					console.log(res);
					//动态获取真实图片宽高
					this.imgwidth = res.width;
					this.imgheight = res.height;
				}
			})
		},

uni.saveImageToPhotosAlbum 保存图片到系统相册

//条件编译  放到onload页面周期内
			// #ifndef H5
			let url = 'https://img2.baidu.com/it/u=297478628,2059211344&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=278';
			uni.downloadFile({
				url:url,
				success: (res) => {
					console.log(res);
					let file = res.tempFilePath;
					//保存到相册api  不支持h5 条件编译
					uni.saveImageToPhotosAlbum({
						filePath:file,
						success: (re) => {
							console.log(re);
						},
						fail: (err) => {
							console.log(err);
						}
					})
				}
			})
			// #endif

uni.compressImage 压缩图片接口,可选压缩质量 不支持h5 把图片变小

//测试压缩图片api
						let temfile = res.tempFilePaths[1];
						uni.getImageInfo({
							src:temfile,
							success: (re) => {
								console.log(re);
								//压缩
								uni.compressImage({
									src:re.path,
									quality:80,
									width:100,
									height:100,
									success: (r) => {
										console.log(JSON.stringify(r));
										let path = r.tempFilePath;
										uni.getImageInfo({
											src:path,
											success: (info) => {
												console.log(info);
											}
										})
									},
									fail: (er) => {
										console.log(er);
									}
								})
							}
						})

视频 跟图片操作相似

设备

系统信息

uni.getSystemInfo 获取系统信息 经常用 屏幕宽度,高度

  • 屏幕高度 = 原生NavigationBar高度(含状态栏高度)+ 可使用窗口高度 + 原生TabBar高度
  • windowHeight不包含NavigationBar和TabBar的高度
  • H5端,windowTop等于NavigationBar高度,windowBottom等于TabBar高度
  • App端,windowTop等于透明状态NavigationBar高度,windowBottom等于透明状态TabBar高度
  • 高度相关信息,要放在 onReady 里获取
//onloaad生命周期
//同步操作会有等待 当建一个异步处理 可以用同步处理 
			let sync = uni.getSystemInfoSync();
			new Promise((resolve,refuse)=>{
				let sync1 = uni.getSystemInfoSync();
				let sync2 = uni.getSystemInfoSync();
				resolve && resolve();
			}).then(res=>{
				
			}).catch(err=>{
				
			})
			
			uni.getSystemInfo({
				success: (res) => {
					console.log(JSON.stringify(res));
				}
			})

uni.canIUse 判断应用的 API,回调,参数,组件等是否在当前版本可用

网络状态

获取网络状态 做直播页面时用 普通页面较少

uni.getNetworkType 获取网络类型

uni.offNetworkStatusChange

<view>{{isconnect}}--{{nettype}}</view>

return {
				isconnect:true,
				nettype:''
			}

//注意获取网络信息,要在页面卸载页面设置关闭获取api
		onLoad() {
			uni.onNetworkStatusChange(function(res){
				console.log('change');
				this.isconnect = res.isConnected;
				this.nettype = res.networkType;
			})
		},
		//关闭获取网络信息
		onUnload() {
			uni.offNetworkStatusChange(function(){
				
			})
		},

拨打电话

uni.makePhoneCall

<button @click="oncallclick">拨打电话</button>

oncallclick(){
				uni.makePhoneCall({
					phoneNumber:'000000000000',
					success: (res) => {
						let timer = setTimeout(()=>{
							console.log(res);
							clearTimeout(timer);
						},2000);
					}
				})
			}

扫描 uni.scanCode

剪切板

uni.setClipboardData 设置系统剪贴板的内容

<button @click="oncopy">剪切板</button>

oncopy(){
				uni.setClipboardData({
					data:'剪切板'
				})
			}

uni.getClipboardData 获取系统剪贴板内容 可以用于类似于拼多多密码口令

<button @click="oncopy">剪切板{{data}}</button>

data:''

oncopy(){
				uni.setClipboardData({
					data:'剪切板'
				})
				uni.getClipboardData({
					success: (res) => {
						console.log(res);
						this.data = res.data;
					}
				})
			}

键盘

uni.hideKeyboard 隐藏已经显示的软键盘,如果软键盘没有显示则不做任何操作

<input placeholder="键盘测试" @input="onhidekey"/>

onhidekey(res){
				// console.log(res);
				let val = res.detail.value;
				console.log(val);
				//条件判断 限制输入长度
				if(val.length>5){
					uni.hideKeyboard();
				}
			}
界面

交互反馈

uni.showToast 显示消息提示框

<button @click="onshowtoast">弹出消息提示框</button>

onshowtoast(){
				uni.showToast({
					title:'弹出消息框',
					duration:30000,  //安卓不支持延迟
					position:'bottom',
					icon:'loading',
					success: (res) => {
						console.log(res);
					}
				})
			},

uni.hideToast 隐藏消息提示框

<button @onhidetoast>隐藏消息框</button>

onhidetoast(){
				uni.hideToast();
			}

uni.showLoading 显示 loading 提示框, 需主动调用 uni.hideLoading 才能关闭提示框

<button @click="onshowloading">显示loading</button>

onshowloading(){
				uni.showLoading({
					title:'loading等待.....',
					mask:false, //true 不可以点击 false 可以
					success: (res) => {
						console.log(res);
					}
				})
			}

uni.hideLoading 隐藏 loading 提示框

onshowloading(){
				uni.showLoading({
					title:'loading等待.....',
					mask:false, //true 不可以点击 false 可以
					success: (res) => {
						console.log(res);
						let timer = setTimeout(()=>{
							uni.hideLoading();
							clearTimeout();
						},3000);
					}
				})
			}

uni.showModal 显示模态弹窗,可以只有一个确定按钮,也可以同时有确定和取消按钮。类似于一个API整合了 html 中:alert、confirm

<button @click="onshowmodel">显示提示框</button>

onshowmodel(){
				uni.showModal({
					title:'提示',
					content:'这是提示',
					showCancel:false,
					confirmText:'你好帅',
					editable:true,
					success: (res) => {
						console.log(res);
						if(res.confirm){  //点击确定时 做后续操作
							console.log('确定');
						}
					}
				})
			}

uni.showActionSheet 从底部向上弹出操作菜单

<button @click="onshowsheet">弹出列表</button>

onshowsheet(){
				let datas = ['选项一','选项二','选项三'];
				uni.showActionSheet({
					itemList:datas,
					success: (res) => {
						console.log(res);
						let select = datas[res.tapIndex];
						console.log(select);
					}
				})
			}

设置导航条

uni.setNavigationBarTitle

onLoad() {
			//动态设置导航标题
			let timer = setTimeout(()=>{
				uni.setNavigationBarTitle({
					title:'新标题'
				})
			},3000)

uni.setNavigationBarColor 动态设置导航颜色

//动态设置导航颜色
			uni.setNavigationBarColor({
				frontColor:'#000000',
				backgroundColor:'#4CD964',
			})

uni.showNavigationBarLoading 在当前页面显示导航条加载动画

设置tabbar

uni.setTabBarItem 动态设置 tabBar 某一项的内容

onLoad() {
			let timer = setTimeout(()=>{
				uni.setTabBarItem({
					index:1,
					text:'api3',
					iconPath:'/static/logo.png',
					pagePath:'/pages/api/api3',
					success: () => {
						uni.setTabBarStyle({
							backgroundRepeat:'repeat'
						})
					}
				})
				clearTimeout(timer);
			},3000)

uni.setTabBarBadge 为 tabBar 某一项的右上角添加文本 微信qq消息提示

onLoad() {
			uni.setTabBarBadge({
				text:'99+',
				index:1
			})
			let timer = setTimeout(()=>{
				uni.setTabBarItem({
					index:1,
					text:'api3',
					iconPath:'/static/logo.png',
					pagePath:'/pages/api/api',
					success: () => {
						uni.setTabBarStyle({
							backgroundRepeat:'repeat'
						})
					}
				})
				//移除右上角文本api
				uni.removeTabBarBadge({
					index:1
				})
				clearTimeout(timer);
			},3000)

动画

uni.createAnimation 创建一个动画实例 调用实例的方法来描述动画。最后通过动画实例的export方法导出动画数据传递给组件的animation属性

<view :animation='animationdata'>动画</view>

animationdata:{}

//创建动画
			let animation = uni.createAnimation({
				duration:3000,
				timingFunction:'linear',
			});
			animation.translateX(100).translateY(100).step();
			this.animationdata = animation.export();

节点信息

页面通讯

uni.$emit 触发全局的自定义事件,附加参数都会传给监听器回调函数

subNVue原生子窗体

  • 7
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

汐瀼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值