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

运行结果:

相关推荐
张较瘦_7 分钟前
前端 | 代码可读性 + SEO 双提升!HTML 语义化标签实战教程
前端·html
似水流年QC16 分钟前
前端国际化实战指南:i18n 工程化最佳实践总结
前端
GISer_Jing17 分钟前
企业级前端脚手架:原理与实战指南
前端·前端框架
非凡ghost21 分钟前
Floorp Browser(基于Firefox火狐浏览器)
前端·windows·学习·firefox·软件需求
hpz122324 分钟前
XHR和Fetch功能对比表格
前端·网络请求
q_191328469525 分钟前
基于SpringBoot+Vue.js的高校竞赛活动信息平台
vue.js·spring boot·后端·mysql·程序员·计算机毕业设计
我是小邵30 分钟前
【踩坑实录】一次 H5 页面在 PC 端的滚动条与轮播图修复全过程(Vue + Vant)
前端·javascript·vue.js
苹果电脑的鑫鑫34 分钟前
Css画圆弧的方法
前端·css
2501_9462309840 分钟前
Cordova&OpenHarmony外观主题设置
android·javascript
军军君0142 分钟前
Three.js基础功能学习一:环境资源及基础知识
开发语言·javascript·学习·3d·前端框架·threejs·三维