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'; 导入是因为下载了插件(具体可查看博客),没有下载的需常规导入)

运行结果:

相关推荐
合作小小程序员小小店13 小时前
web网页开发,在线%物流配送管理%系统,基于Idea,html,css,jQuery,java,ssh,mysql。
java·前端·css·数据库·jdk·html·intellij-idea
三门13 小时前
web接入扣子私有化智能体
前端
林小帅13 小时前
AI “自动驾驶” 的使用分享
前端
起名时在学Aiifox13 小时前
深入解析 Electron 打包中的 EPERM: operation not permitted 错误
前端·javascript·electron
游戏开发爱好者813 小时前
Fiddler抓包工具完整教程 HTTPHTTPS抓包、代理配置与API调试实战技巧(开发者进阶指南)
前端·测试工具·ios·小程序·fiddler·uni-app·webview
hachi031313 小时前
Vue中input disabled时点击事件不触发怎么办?
javascript·vue.js·ecmascript
BestSongC13 小时前
基于VUE和FastAPI的行人目标检测系统
vue.js·人工智能·yolo·目标检测·fastapi
漫天黄叶远飞13 小时前
别再把对象当“字典”!JS 零基础也能看懂的“属性账本”拆解笔记
javascript
华仔啊14 小时前
20个CSS实用技巧,10分钟从小白变大神!
前端·css
起名时在学Aiifox14 小时前
Vue3 + Element Plus 表格排序实战:基于状态字段的智能排序方案
前端·javascript·vue.js·element plus