以公共组件为例
1.创建公共组件-(第四步:传入子组件数据)
//公共组件的页面 ./src/components
<script setup lang="ts">
import type { typeDefine} from '@/types/homeindex'
import { ref } from 'vue'
// 接受父组件的传值
defineProps<{
list: typeDefine[]
}>()
</script>
<template>
<view class="carousel">
<swiper :circular="true" :autoplay="false" :interval="3000">
<swiper-item v-for="item in list" :key="item.id">
{{item.imgUrl}}
</swiper-item>
</swiper>
</view>
</template>
<style lang="scss">
</style>
//类型定义/types/homeindex.d.ts
export type typeDefine= {
id: string
imgUrl: string
}
2.在pages.json的配置
{
// 组件自动引入规则
"easycom": {
// 是否开启自动扫描
"autoscan": true,
// 以正则方式自定义组件匹配规则
"custom": {
// uni-ui 规则如下配置
"^uni-(.*)": "@dcloudio/uni-ui/lib/uni-$1/uni-$1.vue",
// 以 Xtx 开头的组件,在 components 文件夹中查找引入(需要重启服务器)
"^Xtx(.*)": "@/components/Xtx$1.vue"
}
},
"pages":[]
}
3.引入组件-进行数据获取
<script setup lang="ts">
import { FunctionAPI } from '@/services/home'
import type { typeDefine} from '@/types/home'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
const List= ref<typeDefine[]>([])
const getData = async () => {
const res = await FunctionAPI()
List.value = res.result
}
// 页面加载
onLoad(async () => {
isLoading.value = true
await Promise.all([getData(),其他方法()])
isLoading.value = false
})
</script>
<template>
<view >
<XtxSwiper :list="List" />
</view>
</template>
<style lang="scss">
</style>
type Data<T> = {
code: string
msg: string
result: T
}
// 2.2 添加类型,支持泛型
export const http = <T>(options: UniApp.RequestOptions) => {
// 1. 返回 Promise 对象
return new Promise<Data<T>>((resolve, reject) => {
uni.request({
...options,
// 响应成功
success(res) {
// 状态码 2xx, axios 就是这样设计的
if (res.statusCode >= 200 && res.statusCode < 300) {
// 2.1 提取核心数据 res.data
resolve(res.data as Data<T>)
} else if (res.statusCode === 401) {
// 401错误 -> 清理用户信息,跳转到登录页
const memberStore = useMemberStore()
memberStore.clearProfile()
uni.navigateTo({ url: '/pages/login/login' })
reject(res)
} else {
// 其他错误 -> 根据后端错误信息轻提示
uni.showToast({
icon: 'none',
title: (res.data as Data<T>).msg || '请求错误',
})
reject(res)
}
},
// 响应失败
fail(err) {
uni.showToast({
icon: 'none',
title: '网络错误,换个网络试试',
})
reject(err)
},
})
})
}
//接口的定义services/homeindex.ts
export const FunctionAPI = (params) => {
return http<typeDefine[]>({
method: '接口方式',
url: '接口地址',
data: {
params, //接口传参
},
})
}