首頁  >  文章  >  web前端  >  uni-app入門教學之介面的基本使用

uni-app入門教學之介面的基本使用

coldplay.xixi
coldplay.xixi轉載
2021-01-12 09:46:255865瀏覽

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.dow​​nloadFile(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)參數名稱類型必填與否預設值說明url#是#無開發者伺服器介面位址dataObject/String/ArrayBuffer否請求的參數headerObject#否無#設定請求的header,不能設定ReferermethodString否timeoutdataTyperesponseType#否
前言 一、網路請求
是用來發起網路請求的介面。 OBJECT常見參數如下:
##GET 請求方法,包括GET、POST、PUT、DELETE等方法
#Number #60000 #逾時時間,單位ms
String #否 json 如果設為json,會嘗試對傳回的資料做一次JSON.parse
String text
##設定響應的資料類型。合法值:text、arraybuffer success Function
無#####收到開發者伺服器成功傳回的回呼函數############fail######Function######否######無######介面呼叫失敗的回呼函數############complete######Function#######否#######無######介面呼叫結束的回呼函數(調用成功、失敗都會執行)############

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

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

顯示:
uniapp interface network request json post

可以看到,也回傳了資料。

二、圖片處理

1.uni.chooseImage(OBJECT)

從本機相簿選擇圖片或使用相機拍照。

OBJECT常見參數如下:

##介面呼叫失敗的回呼函數小程式、 AppcompleteFunction#介面呼叫結束的回呼函數(呼叫成功、失敗都會執行)
參數名稱 類型 必填與否 說明
count Number 最多可以選擇的圖片張數,預設9
sizeType Array #Nooriginal 原圖,compressed 壓縮圖,預設二者都有
#extension Array 根據檔案拓展名過濾,每一項都不能是空字串。預設不過濾。
sourceType Array album 從相簿選圖,camera 使用相機,預設二者都有。如需直接開啟相機或直接選相冊,請只使用一個選項
success Function 成功則傳回圖片的本機檔案路徑清單tempFilePaths
fail #Function #否
index.vue如下:

<template>
	<view>
		<button type="primary" @click="img">上传图片</button>
	</view></template><script>
	export default {
		data() {
			return {
			}
		},
		onLoad() {
			
		},
		onShow() {
			console.log('index onshow')
		},
		onHide() {
			console.log('index onhide')
		},
		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常見參數如下:

參數名稱類型必填說明currentString/Number因情況而定目前顯示圖片的連結/索引值,不填或填入的值無效則為urls 的第一張#urlsArray##需要預覽的圖片連結清單indicatorString否圖片指示器樣式,可取值:「default ” - 底部圓點指示器; “number” - 頂部數字指示器; “none” - 不顯示指示器loopBoolean否是否可循環預覽,預設值為falselongPressActionsObject
##是
###################################長按圖片顯示操作選單,如不填預設為儲存相簿############success######Function######否######介面呼叫成功的回呼函數############fail######Function#######否######介面呼叫失敗的回呼函數######## ####complete######Function######否######介面呼叫結束的回呼函數(呼叫成功、失敗都會執行)########### #

index.vue如下:

<template>
	<view>
		<button type="primary" @click="img">上传图片</button>
	</view></template><script>
	export default {
		data() {
			return {
			}
		},
		onLoad() {
			
		},
		onShow() {
			console.log('index onshow')
		},
		onHide() {
			console.log('index onhide')
		},
		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 type="primary" @click="img">显示图片</button>
	</view></template><script>
	export default {
		data() {
			return {
			}
		},
		onLoad() {
			
		},
		onShow() {
			console.log('index onshow')
		},
		onHide() {
			console.log('index onhide')
		},
		methods: {
			img: function(){
				uni.previewImage({
					urls: ['https://bkimg.cdn.bcebos.com/pic/95eef01f3a292df56f9e63a6b2315c6034a87320?x-bce-process=image/resize,m_lfit,w_220,h_220,limit_1', 'https://bkimg.cdn.bcebos.com/pic/83025aafa40f4bfb112d51e70d4f78f0f6361880?x-bce-process=image/resize,m_lfit,w_220,h_220,limit_1', 'https://bkimg.cdn.bcebos.com/pic/622762d0f703918f8453f4795f3d269758eec487?x-bce-process=image/resize,m_lfit,w_220,h_220,limit_1']
				})
			}
		}
	}</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 type="primary" @click="img">获取图片信息</button>
	</view></template><script>
	export default {
		data() {
			return {
			}
		},
		onLoad() {
			
		},
		onShow() {
			console.log('index onshow')
		},
		onHide() {
			console.log('index onhide')
		},
		methods: {
			img: function(){
				uni.getImageInfo({
					src: 'https://cn.bing.com/th?id=OHR.HolidayNubble_ZH-CN8122183595_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp',
					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 type="primary" @click="img">上传图片并下载</button>
	</view></template><script>
	export default {
		data() {
			return {}
		},
		onLoad() {

		},
		onShow() {
			console.log('index onshow')
		},
		onHide() {
			console.log('index onhide')
		},
		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('save success');
							}
						})
					}
				})
			}
		}
	}</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 type="primary" @click="img">上传文件</button>
		<progress :percent="percent" stroke-width="20" />
	</view></template><script>
	var _self;
	export default {
		data() {
			return {
				percent: 0
			}
		},
		onLoad() {
			_self = this;
		},
		onShow() {
			console.log('index onshow')
		},
		onHide() {
			console.log('index onhide')
		},
		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: 'file',
							success:function(upres){
								console.log(upres)
							}
						});
						uper.onProgressUpdate(function(prores){
							_self.percent = prores.progress;
							console.log('上传进度'+prores.progress);
							console.log('已上传数据长度'+prores.totalBytesSent);
							console.log('预期需要上传数据总长度'+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 type="primary" @click="img">下载文件</button>
		<progress :percent="percent" stroke-width="20" />
	</view></template><script>
	var _self;
	export default {
		data() {
			return {
				percent: 0,
			}
		},
		onLoad() {
			_self = this;
		},
		onShow() {
			console.log('index onshow')
		},
		onHide() {
			console.log('index onhide')
		},
		methods: {
			img: function() {
				const down = uni.downloadFile({
					url: 'https://bkimg.cdn.bcebos.com/pic/95eef01f3a292df56f9e63a6b2315c6034a87320?x-bce-process=image/resize,m_lfit,w_220,h_220,limit_1',
					success: function(res) {
						if (res.statusCode === 200) {
							console.log(res);
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success: function() {
									console.log('save success');
								}
							})
						}
					}
				});
				down.onProgressUpdate((prores) => {
					_self.percent = prores.progress;
					console.log('下载进度' + prores.progress);
					console.log('已下载数据长度' + prores.totalBytesWritten);
					console.log('预期下载数据总长度' + 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 type="primary" @click="asyncsave">异步保存数据</button>
		<button type="primary" @click="syncsave">同步保存数据</button>
	</view></template><script>
	export default {
		data() {
			return {}
		},
		onLoad() {
		},
		onShow() {
			console.log('index onshow')
		},
		onHide() {
			console.log('index onhide')
		},
		methods: {
			asyncsave: function(){
				uni.setStorage({
					key: 'name',
					data: 'Corley',
					fail:function(){
						console.log('Save failed')
					}
				});
			},
			syncsave: function(){
				try{
					uni.setStorageSync('age', '18')
				}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 type="primary" @click="asyncget">异步获取数据</button>
		<button type="primary" @click="syncget">同步获取数据</button>
	</view></template><script>
	export default {
		data() {
			return {}
		},
		onLoad() {
			uni.setStorage({
				key: 'name',
				data: 'Corley',
				fail:function(){
					console.log('Save failed')
				}
			});
			try{
				uni.setStorageSync('age', '18')
			}catch(e){
				console.log(e)
			}
		},
		onShow() {
			console.log('index onshow')
		},
		onHide() {
			console.log('index onhide')
		},
		methods: {
			asyncget: function(){
				uni.getStorage({
					key: 'age',
					success: function (res) {
						console.log('age:'+res.data);
					}
				})
			},
			syncget: function(){
				try{
					const name = uni.getStorageSync('name');
					if (name){
						console.log('name:'+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 type="primary" @click="asyncremove">异步删除数据</button>
		<button type="primary" @click="syncremove">同步删除数据</button>
	</view></template><script>
	export default {
		data() {
			return {}
		},
		onLoad() {
			uni.setStorage({
				key: 'name',
				data: 'Corley',
				fail:function(){
					console.log('Save failed')
				}
			});
			try{
				uni.setStorageSync('age', '18')
			}catch(e){
				console.log(e)
			}
		},
		onShow() {
			console.log('index onshow')
		},
		onHide() {
			console.log('index onhide')
		},
		methods: {
			asyncremove: function(){
				uni.removeStorage({
					key: 'age',
					success: function (res) {
						console.log('async remove success');
					}
				})
			},
			syncremove: function(){
				try{
					uni.removeStorageSync('name');
					console.log('sync remove success');
				}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中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除