Home Web Front-end uni-app Basic use of interfaces in uni-app introductory tutorial

Basic use of interfaces in uni-app introductory tutorial

Jan 12, 2021 am 09:46 AM
uni-app

Basic use of interfaces in uni-app introductory tutorial

Recommended (free): uni-app development tutorial

Article Directory

  • Preface
  • 1. Network request
  • 2. Image processing
    • 1.uni.chooseImage(OBJECT)
    • 2.uni.previewImage(OBJECT)
    • 3.uni.getImageInfo(OBJECT)
    • 4.uni.saveImageToPhotosAlbum(OBJECT)
  • 3. File upload and download
    • 1.uni.uploadFile(OBJECT)
    • 2.uni.downloadFile(OBJECT)
  • 4. Data caching
    • 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)
  • Summary

Foreword

This article mainly introduces some basic interfaces provided by uni-app, including: Network The request interface is used to carry specific data through the specified request method, request to a specific address and return the request result; the image processing interface includes selection, preview, information acquisition, saving to local interfaces, etc.; the file processing interface includes files Upload and download interfaces; data caching interfaces, including interfaces for saving, obtaining or deleting data in a synchronous or asynchronous manner.

1. Network Request

If the applet wants to operate normally, it needs to interact with the server for data, which is generally implemented through the interface.
Data interaction is generally implemented through the network request interface.

uni.request(OBJECT) is the interface used to initiate network requests.

OBJECT common parameters are as follows:

Parameter name Type Required or not Default value Description
url String is None Developer server interface address
data Object/String/ArrayBuffer No None Request parameters
header Object No None Set request header, cannot set Referer
method String No GET request method, including GET, POST, PUT, DELETE and other methods
timeout Number No 60000 Timeout Time, unit ms
dataType String No json If set to json, it will Try doing a JSON.parse on the returned data
responseType String No text Set the data type of the response. Legal values: text, arraybuffer
success Function No None Received from developer The callback function returned successfully by the server
fail Function No None The interface call failed Callback function
complete Function No None The callback function at the end of the interface call (call Both success and failure will be executed)

Use the GET method to make a normal request. The index.vue is as follows:

<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>
Copy after login

Display:
uniapp interface network request

You can see that the data data is returned after the request.

Note:
When each mini program platform is running, the network-related API needs to be configured with a domain name whitelist before use. Therefore, when using the mini program for testing, the domain name needs to be set in the WeChat Developer Center. Or do not verify the legal domain name in the local configuration of the project, as follows:
uniapp interface network domain close

Then request json data and use the POST method to request, as follows:

<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>
Copy after login

Display:
uniapp interface network request json post

You can see that the data is also returned.

2. Image processing

1.uni.chooseImage(OBJECT)

Choose a picture from the local album or use the camera Photograph.

OBJECT common parameters are as follows:

Parameter name Type Required or not Description
count Number No The maximum number of pictures that can be selected, default 9
sizeType Array No original original image, compressed compressed image, both are available by default
extension Array No Filter based on file extension, each item cannot be an empty string. No filtering by default.
sourceType Array No album Select pictures from the album, camera uses the camera, and both are available by default. If you need to open the camera directly or select an album directly, please use only one option
success Function is success Returns the local file path list of the image tempFilePaths
fail Function No Callback function applet for failed interface call, App
complete Function No The callback function at the end of the interface call (will be executed if the call is successful or failed)

index.vue is as follows:

<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>
Copy after login

Display:
uniapp interface image choose

You can see that after the upload is successful, the result is returned Path link to temporary image.

2.uni.previewImage(OBJECT)

Preview image.

OBJECT common parameters are as follows:

##longPressActionsObjectNo Long press the picture to display the operation menu. If not filled in, the default is to save the albumsuccessFunctionNoInterface call successful The callback functionfailFunctionNoThe callback function that fails to call the interfacecompleteFunctionNoThe callback function at the end of the interface call (will be executed if the call is successful or failed)

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>
Copy after login

显示:
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>
Copy after login

显示:
uniapp interface image preview outside

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

3.uni.getImageInfo(OBJECT)

获取图片信息。

OBJECT常见参数和含义如下:

Parameter name Type Required Description
current String/Number Depends on the situation The link of the currently displayed image/ Index value, if left blank or filled in with an invalid value, the first
urls Array is List of picture links that need to be previewed
indicator String No Picture indicator style, possible value: "default " - bottom dot indicator; "number" - top number indicator; "none" - no indicator shown
loop Boolean No Whether the preview can be looped, the default value is false
参数名 类型 必填 说明
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>
Copy after login

显示:
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>
Copy after login

显示:
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>
Copy after login

显示:
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>
Copy after login

显示:
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>
Copy after login

显示:
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>
Copy after login

显示:
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>
Copy after login

显示:
uniapp interface datacache remove

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

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

总结

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

The above is the detailed content of Basic use of interfaces in uni-app introductory tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to develop uni-app in VSCode? (Tutorial sharing) How to develop uni-app in VSCode? (Tutorial sharing) May 13, 2022 pm 08:11 PM

How to develop uni-app in VSCode? The following article will share with you a tutorial on developing uni-app in VSCode. This may be the best and most detailed tutorial. Come and take a look!

Use uniapp to develop a simple map navigation Use uniapp to develop a simple map navigation Jun 09, 2022 pm 07:46 PM

How to use uniapp to develop a simple map navigation? This article will provide you with an idea for making a simple map. I hope it will be helpful to you!

Let's talk about how to use uniapp to develop a snake game! Let's talk about how to use uniapp to develop a snake game! May 20, 2022 pm 07:56 PM

How to use uniapp to develop a snake game? The following article will take you step by step to implement the Snake game in uniapp. I hope it will be helpful to you!

How to encapsulate uni-app vue3 interface request How to encapsulate uni-app vue3 interface request May 11, 2023 pm 07:28 PM

uni-app interface, global method encapsulation 1. Create an api file in the root directory, create api.js, baseUrl.js and http.js files in the api folder 2.baseUrl.js file code exportdefault"https://XXXX .test03.qcw800.com/api/"3.http.js file code exportfunctionhttps(opts,data){lethttpDefaultOpts={url:opts.url,data:data,method:opts.method

Take you step by step to develop a uni-app calendar plug-in (and publish it) Take you step by step to develop a uni-app calendar plug-in (and publish it) Jun 30, 2022 pm 08:13 PM

This article will guide you step by step in developing a uni-app calendar plug-in, and introduce how the next calendar plug-in is developed from development to release. I hope it will be helpful to you!

Examples to explain how uniapp implements the all-select function of multi-select boxes Examples to explain how uniapp implements the all-select function of multi-select boxes Jun 22, 2022 am 11:57 AM

This article brings you relevant knowledge about uniapp, which mainly organizes the related issues of implementing the select-all function of the multi-select box. The reason why the select-all function cannot be implemented is that when the checked field of the checkbox is dynamically modified, the status on the interface can Real-time changes, but the change event of checkbox-group cannot be triggered. Let's take a look at it. I hope it will be helpful to everyone.

Let's talk about uniapp's scroll-view drop-down loading Let's talk about uniapp's scroll-view drop-down loading Jul 14, 2022 pm 09:07 PM

How does uniapp implement scroll-view drop-down loading? The following article talks about the drop-down loading of the uniapp WeChat applet scroll-view. I hope it will be helpful to everyone!

Detailed example of how uniapp implements phone recording function (with code) Detailed example of how uniapp implements phone recording function (with code) Jan 05, 2023 pm 04:41 PM

This article brings you relevant knowledge about uniapp. It mainly introduces how to use uniapp to make calls and synchronize recording. Friends who are interested should take a look at it. I hope it will be helpful to everyone.

See all articles