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

运行结果:

相关推荐
打瞌睡的朱尤10 小时前
day8 Vue-x
前端·javascript·vue.js
Web打印10 小时前
Phpask(php集成环境)之04配置网站
开发语言·前端·php
一只大侠的侠10 小时前
React Native for OpenHarmony:Calendar 日历组件实现指南
javascript·react native·react.js
Highcharts.js10 小时前
矩形树图Treemap布局算法深度解析:基于Highcharts实现带层级交互的矩形树图
javascript·交互·开发文档·treemap·highcharts·图表类型·矩形树图
一只大侠的侠10 小时前
React Native for OpenHarmony:日期选择功能完整实现指南
javascript·react native·react.js
Zhencode10 小时前
vue3运行时核心模块之runtime-dom
前端·javascript·vue.js
henry10101010 小时前
DeepSeek生成的网页版念经小助手
javascript·css·html5·工具
一只大侠的侠10 小时前
React Native实战:高性能StickyHeader粘性标题组件实现
javascript·react native·react.js
夏幻灵10 小时前
CSS 布局深究:行框模型、幽灵节点与绝对居中的数学原理
前端·css
打瞌睡的朱尤10 小时前
Vue day13~16Vue特性,Pinia,大事件项目
前端·javascript·vue.js