登录  /  注册
首页 > web前端 > uni-app > 正文

uni-app入门教程之接口的基本使用

coldplay.xixi
发布: 2021-01-12 09:46:25
转载
5701人浏览过

uni-app入门教程之接口的基本使用

推荐(免费):uni-app开发教程

文章目录

  • 前言
  • 一、网络请求
  • 二、图片处理
    • 1.uni.chooseImage(OBJECT)
    • 2.uni.previewImage(OBJECT)
    • 3.uni.getImageInfo(OBJECT)
    • 4.uni.saveImageToPhotosAlbum(OBJECT)
  • 三、文件上传和下载
    • 1.uni.uploadFile(OBJECT)
    • 2.uni.downloadFile(OBJECT)
  • 四、数据缓存
    • 1.uni.setStorage(OBJECT)
    • 2.uni.setStorageSync(KEY,DATA)
    • 3.uni.getStorage(OBJECT)
    • 4.uni.getStorageSync(KEY)
    • 5.uni.removeStorage(OBJECT)
    • 6.uni.removeStorageSync(KEY)
  • 总结

前言

本文主要介绍uni-app提供的一些基础接口,包括:网络请求接口,用于通过指定的请求方法,携带特定的数据,向特定的地址请求并返回请求结果;图片处理接口,包括选择、预览、获取信息、保存到本地等接口;文件处理接口,包括文件上传和下载接口;数据缓存接口,包括以同步或异步的方式保存、获取或删除数据的接口。

一、网络请求

小程序要想正常运转,都需要与服务器端进行数据交互,一般都通过接口实现。
数据交互一般都会通过网络请求接口实现。

uni.request(OBJECT)是用于发起网络请求的接口。

OBJECT常见参数如下:

参数名 类型 必填与否 默认值 说明
url String 开发者服务器接口地址
data Object/String/ArrayBuffer 请求的参数
header Object 设置请求的 header,不能设置 Referer
method String GET 请求方法,包括GET、POST、PUT、DELETE等方法
timeout Number 60000 超时时间,单位 ms
dataType String json 如果设为 json,会尝试对返回的数据做一次 JSON.parse
responseType String text 设置响应的数据类型。合法值:text、arraybuffer
success Function 收到开发者服务器成功返回的回调函数
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

使用GET方法进行普通请求,index.vue如下:

<template><view>
		{{res}}	</view></template><script>
	export default {
		data() {
			return {
				res:&#39;&#39;
			}
		},
		onLoad() {
			uni.request({
				url:&#39;https://demo.hcoder.net&#39;,
				method: &#39;GET&#39;,
				success:function(res){
					console.log(res)
				}
			})
		},
		onShow() {
			console.log(&#39;index onshow&#39;)
		},
		onHide() {
			console.log(&#39;index onhide&#39;)
		},
		methods: {
		}
	}</script><style>
	</style>
登录后复制

显示:
uniapp interface network request

可以看到,请求后返回了data数据。

说明:
在各个小程序平台运行时,网络相关的API在使用前需要配置域名白名单,因此在使用小程序进行测试时,需要在微信开发者中心设置域名,或者在项目的本地配置中不校验合法域名,如下:
uniapp interface network domain close

再请求json数据和使用POST方法请求,如下:

<template><view>
		{{res}}	</view></template><script>
	export default {
		data() {
			return {
				res: &#39;&#39;
			}
		},
		onLoad() {
			const request1 = uni.request({
				url: &#39;https://demo.hcoder.net/index.php?m=getJson&#39;,
				success: function(res) {
					console.log(res.data);
				}
			});
			//
			const request2 = uni.request({
				url: &#39;https://demo.hcoder.net/index.php&#39;,
				data: {
					name: &#39;Corley&#39;,
					&#39;age&#39;: 18
				},
				method: "POST",
				header: {
					&#39;content-type&#39;: &#39;application/x-www-form-urlencoded&#39;
				},
				success: function(res) {
					console.log(res.data);
				}
			});
		},
		onShow() {
			console.log(&#39;index onshow&#39;)
		},
		onHide() {
			console.log(&#39;index onhide&#39;)
		},
		methods: {}
	}</script><style></style>
登录后复制

显示:
uniapp interface network request json post

可以看到,也返回了数据。

二、图片处理

1.uni.chooseImage(OBJECT)

从本地相册选择图片或使用相机拍照。

OBJECT常见参数如下:

参数名 类型 必填与否 说明
count Number 最多可以选择的图片张数,默认9
sizeType Array 否 original 原图,compressed 压缩图,默认二者都有
extension Array 根据文件拓展名过滤,每一项都不能是空字符串。默认不过滤。
sourceType Array album 从相册选图,camera 使用相机,默认二者都有。如需直接开相机或直接选相册,请只使用一个选项
success Function 成功则返回图片的本地文件路径列表 tempFilePaths
fail Function 接口调用失败的回调函数 小程序、App
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

index.vue如下:

<template><view><button>上传图片</button>
	</view></template><script>
	export default {
		data() {
			return {
			}
		},
		onLoad() {
			
		},
		onShow() {
			console.log(&#39;index onshow&#39;)
		},
		onHide() {
			console.log(&#39;index onhide&#39;)
		},
		methods: {
			img: function(){
				uni.chooseImage({
					count: 9,
					sizeType:"compressed",
					success:function(res){
						console.log(res)
					}
				})
			}
		}
	}</script><style></style>
登录后复制

显示:
uniapp interface image choose

可以看到,上传成功后,结果返回了临时图片的路径链接。

2.uni.previewImage(OBJECT)

预览图片。

OBJECT常见参数如下:

参数名 类型 必填 说明
current String/Number 因情况而定 当前显示图片的链接/索引值,不填或填写的值无效则为 urls 的第一张
urls Array 需要预览的图片链接列表
indicator String 图片指示器样式,可取值:“default” - 底部圆点指示器; “number” - 顶部数字指示器; “none” - 不显示指示器
loop Boolean 是否可循环预览,默认值为 false
longPressActions Object 长按图片显示操作菜单,如不填默认为保存相册
success Function 接口调用成功的回调函数
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

index.vue如下:

<template><view><button>上传图片</button>
	</view></template><script>
	export default {
		data() {
			return {
			}
		},
		onLoad() {
			
		},
		onShow() {
			console.log(&#39;index onshow&#39;)
		},
		onHide() {
			console.log(&#39;index onhide&#39;)
		},
		methods: {
			img: function(){
				uni.chooseImage({
					count: 9,
					sizeType:"compressed",
					success:function(res){
						console.log(res);
						uni.previewImage({
							urls: res.tempFilePaths,
						})
					}
				})
			}
		}
	}</script><style></style>
登录后复制

显示:
uniapp interface image preview

可以看到,在调用uni.chooseImage上传图片后,成功时的回调函数中再调用uni.previewImage,即可实现预览。

被预览的图片链接,除了可以是uni.chooseImage上传生成的内部临时图片,还可以是自定义的外部图片,如下:

<template><view><button>显示图片</button>
	</view></template><script>
	export default {
		data() {
			return {
			}
		},
		onLoad() {
			
		},
		onShow() {
			console.log(&#39;index onshow&#39;)
		},
		onHide() {
			console.log(&#39;index onhide&#39;)
		},
		methods: {
			img: function(){
				uni.previewImage({
					urls: [&#39;https://bkimg.cdn.bcebos.com/pic/95eef01f3a292df56f9e63a6b2315c6034a87320?x-bce-process=image/resize,m_lfit,w_220,h_220,limit_1&#39;, &#39;https://bkimg.cdn.bcebos.com/pic/83025aafa40f4bfb112d51e70d4f78f0f6361880?x-bce-process=image/resize,m_lfit,w_220,h_220,limit_1&#39;, &#39;https://bkimg.cdn.bcebos.com/pic/622762d0f703918f8453f4795f3d269758eec487?x-bce-process=image/resize,m_lfit,w_220,h_220,limit_1&#39;]
				})
			}
		}
	}</script><style></style>
登录后复制

显示:
uniapp interface image preview outside

可以看到,外部图片也可以正常显示。

3.uni.getImageInfo(OBJECT)

获取图片信息。

OBJECT常见参数和含义如下:

参数名 类型 必填 说明
src String 图片的路径,可以是相对路径、临时文件路径、存储文件路径、网络图片路径
success Function 接口调用成功的回调函数
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

index.vue如下:

<template><view><button>获取图片信息</button>
	</view></template><script>
	export default {
		data() {
			return {
			}
		},
		onLoad() {
			
		},
		onShow() {
			console.log(&#39;index onshow&#39;)
		},
		onHide() {
			console.log(&#39;index onhide&#39;)
		},
		methods: {
			img: function(){
				uni.getImageInfo({
					src: &#39;https://cn.bing.com/th?id=OHR.HolidayNubble_ZH-CN8122183595_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp&#39;,
					success: function(res){
						console.log(res)
					}
				})
			}
		}
	}</script><style></style>
登录后复制

显示:
uniapp interface image getinfo

可以看到,获取到了图片的大小、类型和方向等信息。

4.uni.saveImageToPhotosAlbum(OBJECT)

保存图片到系统相册。

OBJECT常见参数如下:

参数名 类型 必填 说明
filePath String 图片文件路径,可以是临时文件路径也可以是永久文件路径,不支持网络图片路径
success Function 接口调用成功的回调函数
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

index.vue如下:

<template><view><button>上传图片并下载</button>
	</view></template><script>
	export default {
		data() {
			return {}
		},
		onLoad() {

		},
		onShow() {
			console.log(&#39;index onshow&#39;)
		},
		onHide() {
			console.log(&#39;index onhide&#39;)
		},
		methods: {
			img: function() {
				uni.chooseImage({
					count: 9,
					sizeType: "compressed",
					success: function(res) {
						console.log(res);
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePaths[0],
							success:function(){
								console.log(&#39;save success&#39;);
							}
						})
					}
				})
			}
		}
	}</script><style></style>
登录后复制

显示:
uniapp interface image save

可以看到,可以实现将图片保存到本地,并且图片信息一致。

三、文件上传和下载

1.uni.uploadFile(OBJECT)

将本地资源上传到开发者服务器,客户端发起一个 POST 请求,其中 content-type 为 multipart/form-data

OBJECT常见参数如下:

参数名 类型 必填 说明
url String 开发者服务器 url
files Array 需要上传的文件列表。使用 files 时,filePath 和 name 不生效
fileType String 平台之间存在关系 文件类型,image/video/audio
file File 要上传的文件对象
filePath String 要上传文件资源的路径
name String 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
header Object HTTP 请求 Header, header 中不能设置 Referer
timeout Number 超时时间,单位 ms
formData Object HTTP 请求中其他额外的 form data
success Function 接口调用成功的回调函数
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

index.vue如下:

<template><view><button>上传文件</button>
		<progress></progress></view></template><script>
	var _self;
	export default {
		data() {
			return {
				percent: 0
			}
		},
		onLoad() {
			_self = this;
		},
		onShow() {
			console.log(&#39;index onshow&#39;)
		},
		onHide() {
			console.log(&#39;index onhide&#39;)
		},
		methods: {
			img: function() {
				uni.chooseImage({
					count: 1,
					sizeType: ["compressed"],
					success: function(res) {
						var imgFile = res.tempFilePaths[0];
						console.log(imgFile);
						var uper = uni.uploadFile({
							url: "https://demo.hcoder.net/index.php?c=uperTest",
							filePath: imgFile,
							name: &#39;file&#39;,
							success:function(upres){
								console.log(upres)
							}
						});
						uper.onProgressUpdate(function(prores){
							_self.percent = prores.progress;
							console.log(&#39;上传进度&#39;+prores.progress);
							console.log(&#39;已上传数据长度&#39;+prores.totalBytesSent);
							console.log(&#39;预期需要上传数据总长度&#39;+prores.totalBytesExpectedToSend);
						})
					}
				})
			}
		}
	}</script><style></style>
登录后复制

显示:
uniapp interface file upload

可以看到,在上传图片文件之后,获取到了实时的上传进度、并在进度条中同步显示。

除了使用uni.uploadFile(OBJECT),还可以使用更好的APIuniCloud.uploadFile,uniCloud提供了免费CDN和更好的易用性,包括安全的cdn直传。

2.uni.downloadFile(OBJECT)

下载文件资源到本地,客户端直接发起一个 HTTP GET 请求,返回文件的本地临时路径。

OBJECT常见参数如下:

参数名 类型 必填与否 说明
url String 下载资源的 url
header Object HTTP 请求 Header, header 中不能设置 Referer
timeout Number 超时时间,单位 ms
success Function 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: ‘文件的临时路径’}
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

index.vue如下:

<template><view><button>下载文件</button>
		<progress></progress></view></template><script>
	var _self;
	export default {
		data() {
			return {
				percent: 0,
			}
		},
		onLoad() {
			_self = this;
		},
		onShow() {
			console.log(&#39;index onshow&#39;)
		},
		onHide() {
			console.log(&#39;index onhide&#39;)
		},
		methods: {
			img: function() {
				const down = uni.downloadFile({
					url: &#39;https://bkimg.cdn.bcebos.com/pic/95eef01f3a292df56f9e63a6b2315c6034a87320?x-bce-process=image/resize,m_lfit,w_220,h_220,limit_1&#39;,
					success: function(res) {
						if (res.statusCode === 200) {
							console.log(res);
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success: function() {
									console.log(&#39;save success&#39;);
								}
							})
						}
					}
				});
				down.onProgressUpdate((prores) => {
					_self.percent = prores.progress;
					console.log(&#39;下载进度&#39; + prores.progress);
					console.log(&#39;已下载数据长度&#39; + prores.totalBytesWritten);
					console.log(&#39;预期下载数据总长度&#39; + prores.totalBytesExpectedToWrite);
				});
			}
		}
	}</script><style></style>
登录后复制

显示:
uniapp interface file download

可以下载图片到本地并保存。

四、数据缓存

在APP或者小程序中,可以利用本地存储来保存一些数据,比如用户登录数据,在使用用户名密码或者第三方登录方式进行登录后,会将用户信息保存到服务器端,会将用户id和用户随机码(与用户匹配)以键值对的形式到本地,每次与远程进行交互时,都会将保存下来的用户数据发送到远程进行校验。

1.uni.setStorage(OBJECT)

将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个异步接口,可以在存储的同时进行其他操作。

OBJECT参数及其意义如下:

参数名 类型 必填与否 说明
key String 本地缓存中的指定的 key
data Any 需要存储的内容,只支持原生类型、及能够通过 JSON.stringify 序列化的对象
success Function 接口调用成功的回调函数
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

2.uni.setStorageSync(KEY,DATA)

将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口,需要在数据存储完成之后才能进行其他操作。

参数及其意义如下:

参数名 类型 必填与否 说明
key String 本地缓存中的指定的 key
data Any 需要存储的内容,只支持原生类型、及能够通过 JSON.stringify 序列化的对象

在使用uni.setStorageSync(KEY,DATA)存储数据时,需要使用try...catch...语句块捕捉异常。

setStoragesetStorageSync的简单使用如下:

<template><view><button>异步保存数据</button>
		<button>同步保存数据</button>
	</view></template><script>
	export default {
		data() {
			return {}
		},
		onLoad() {
		},
		onShow() {
			console.log(&#39;index onshow&#39;)
		},
		onHide() {
			console.log(&#39;index onhide&#39;)
		},
		methods: {
			asyncsave: function(){
				uni.setStorage({
					key: &#39;name&#39;,
					data: &#39;Corley&#39;,
					fail:function(){
						console.log(&#39;Save failed&#39;)
					}
				});
			},
			syncsave: function(){
				try{
					uni.setStorageSync(&#39;age&#39;, &#39;18&#39;)
				}catch(e){
					console.log(e)
				}
			}
		}
	}</script><style></style>
登录后复制

显示:
uniapp interface datacache set

可以看到,两种方式都将数据保存下来。

3.uni.getStorage(OBJECT)

从本地缓存中异步获取指定 key 对应的内容。

OBJECT 参数及其含义如下:

参数名 类型 必填与否 说明
key String 本地缓存中的指定的 key
success Function 接口调用的回调函数,res = {data: key对应的内容}
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

4.uni.getStorageSync(KEY)

从本地缓存中同步获取指定 key 对应的内容。

参数及其含义如下:

参数名 类型 必填与否 说明
key String 本地缓存中的指定的 key

getStorageSync也需要使用try...catch...语句块捕捉异常。

getStoragegetStorageSync的简单使用如下:

<template><view><button>异步获取数据</button>
		<button>同步获取数据</button>
	</view></template><script>
	export default {
		data() {
			return {}
		},
		onLoad() {
			uni.setStorage({
				key: &#39;name&#39;,
				data: &#39;Corley&#39;,
				fail:function(){
					console.log(&#39;Save failed&#39;)
				}
			});
			try{
				uni.setStorageSync(&#39;age&#39;, &#39;18&#39;)
			}catch(e){
				console.log(e)
			}
		},
		onShow() {
			console.log(&#39;index onshow&#39;)
		},
		onHide() {
			console.log(&#39;index onhide&#39;)
		},
		methods: {
			asyncget: function(){
				uni.getStorage({
					key: &#39;age&#39;,
					success: function (res) {
						console.log(&#39;age:&#39;+res.data);
					}
				})
			},
			syncget: function(){
				try{
					const name = uni.getStorageSync(&#39;name&#39;);
					if (name){
						console.log(&#39;name:&#39;+name);
					}
				}catch(e){
					console.log(e);
				}
			}
		}
	}</script><style></style>
登录后复制

显示:
uniapp interface datacache get

可以获取到之前保存下来的数据。

5.uni.removeStorage(OBJECT)

从本地缓存中异步移除指定 key。

OBJECT 参数及其含义如下:

参数名 类型 必填与否 说明
key String 本地缓存中的指定的 key
success Function 接口调用的回调函数
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

6.uni.removeStorageSync(KEY)

从本地缓存中同步移除指定 key。

参数说明:

参数名 类型 必填与否 说明
key String 本地缓存中的指定的 key

removeStorageremoveStorageSync的简单使用如下:

<template><view><button>异步删除数据</button>
		<button>同步删除数据</button>
	</view></template><script>
	export default {
		data() {
			return {}
		},
		onLoad() {
			uni.setStorage({
				key: &#39;name&#39;,
				data: &#39;Corley&#39;,
				fail:function(){
					console.log(&#39;Save failed&#39;)
				}
			});
			try{
				uni.setStorageSync(&#39;age&#39;, &#39;18&#39;)
			}catch(e){
				console.log(e)
			}
		},
		onShow() {
			console.log(&#39;index onshow&#39;)
		},
		onHide() {
			console.log(&#39;index onhide&#39;)
		},
		methods: {
			asyncremove: function(){
				uni.removeStorage({
					key: &#39;age&#39;,
					success: function (res) {
						console.log(&#39;async remove success&#39;);
					}
				})
			},
			syncremove: function(){
				try{
					uni.removeStorageSync(&#39;name&#39;);
					console.log(&#39;sync remove success&#39;);
				}catch(e){
					console.log(e);
				}
			}
		}
	}</script><style></style>
登录后复制

显示:
uniapp interface datacache remove

此时可以删除指定的数据。

uni.getStorageInfo(OBJECT)uni.getStorageInfoSync()用于异步和同步获取当前 storage 的相关信息,uni.clearStorage()uni.clearStorageSync()用于异步和同步清理本地数据缓存,它们的用法与前3组接口类似。

总结

uni-app提供的的js接口包括标准ECMAScript的js API 和 uni 扩展 API 两部分,每个接口都能实现特定的功能,可以根据具体需要选择使用,来进一步加快开发效率。

以上就是uni-app入门教程之接口的基本使用的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:CSDN网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号