uni-app发起网络请求的三种方式

uni.request(OBJECT)

发起网络请求

具体参数可查看官方文档uni-app

data:请求的参数;

header:设置请求的 header,header 中不能设置 Referer;

method:请求方法;

timeout:超时时间,单位 ms(默认60000);

dataType:如果设为 json,会对返回的数据进行一次 JSON.parse,非 json 不会进行 JSON.parse;

....

免费测试api接口:https://jsonplaceholder.typicode.com/

第一种

html 复制代码
<template>

</template>

<script setup>

	function request(){
		uni.request({
			url:"https://jsonplaceholder.typicode.com/posts", //开发者服务器接口地址
			method:"post",   //请求方法
            success:res=>{   //收到开发者服务器成功返回的回调函数
				console.log(res);
			}
		})
	}

	request();

</script>

<style lang="scss" scoped>
     
</style>

第二种

html 复制代码
<template>
	
</template>

<script setup>

	function request(){
		uni.request({
			url:"https://jsonplaceholder.typicode.com/posts"
		}).then(res=>{
			arrs.value=res.data
		})
	}
   
	request();

</script>

<style lang="scss" scoped>
	   
</style>

第三种

异步同步化

html 复制代码
<template>
	
</template>

<script setup>

   async function request(){
	   let res = await uni.request({
	   	url:"https://jsonplaceholder.typicode.com/posts"
	   })
	   arrs.value=res.data
   }
	
	request();

</script>

<style lang="scss" scoped>
	   
</style>

示例:

html 复制代码
<template>
	<view class="out" v-for="item in arrs">
		<view class="title">{{item.title}}</view>
		<view class="content">{{item.body}}</view>
	</view>
</template>

<script setup>

	let arrs = ref();
	
	function request(){
		uni.request({
			url:"https://jsonplaceholder.typicode.com/posts"
		}).then(res=>{
			arrs.value=res.data
		})
	}
	
	request();
</script>

<style lang="scss" scoped>
	.out{
		padding: 30rpx;
		.title{
			font-size: 40rpx;
		}
		.content{
			margin: 15rpx 0;
			border-bottom: 1px solid #696969;
			color: #696969;
		}
	}       
</style>

( 注:ref 没有使用 import { ref } from 'vue'; 导入是因为下载了插件(具体可查看博客),没有下载的需常规导入)

运行结果:

相关推荐
一斤代码1 小时前
vue3 下载图片(标签内容可转图)
前端·javascript·vue
中微子1 小时前
React Router 源码深度剖析解决面试中的深层次问题
前端·react.js
光影少年2 小时前
从前端转go开发的学习路线
前端·学习·golang
中微子2 小时前
React Router 面试指南:从基础到实战
前端·react.js·前端框架
3Katrina2 小时前
深入理解 useLayoutEffect:解决 UI "闪烁"问题的利器
前端·javascript·面试
前端_学习之路3 小时前
React--Fiber 架构
前端·react.js·架构
coderlin_3 小时前
BI布局拖拽 (1) 深入react-gird-layout源码
android·javascript·react.js
伍哥的传说3 小时前
React 实现五子棋人机对战小游戏
前端·javascript·react.js·前端框架·node.js·ecmascript·js
qq_424409193 小时前
uniapp的app项目,某个页面长时间无操作,返回首页
前端·vue.js·uni-app
我在北京coding3 小时前
element el-table渲染二维对象数组
前端·javascript·vue.js