1.在src文件夹创建models文件夹
import { user } from "@/service/api"
//用户信息返回的数据类型
interface userInfoType {
username: string,
phone: string
}
//返回类型
interface ResultType<T> {
errno: number,
errmsg: string,
datas: T
}
class userModel {
datas: ResultType<userInfoType> = {
errno: 0, errmsg: "", datas: {
username: "",
phone: ""
}
}
async getInfo() {
uni.showLoading({
title: "加载中",
})
let redatas = await user.getUserInfo<userInfoType>()
if (redatas.errno == 0) {
this.datas = redatas
}
uni.hideLoading()
}
}
export { userModel }
export type { ResultType, userInfoType }
2.修改src/service/module/user.ts,使其改成ts写法
import type { ResultType } from "@/models/userModel"
import service from "../service"
const user = {
getUserInfo<T>(): Promise<ResultType<T>> {
return service.post<Promise<ResultType<T>>>("/api/getUserInfo", {})
}
}
export default user
3.在页面中使用
<template>
<view class="content">
<image class="logo" src="/static/logo.png" />
<view class="text-area">
<text class="title">{{ title }}-{{ userObj.datas.datas.username }}</text>
</view>
</view>
</template>
<script setup lang="ts">
import { reactive, ref } from "vue"
import { userModel } from "@/models/userModel"
const userObj = reactive(new userModel())
userObj.getInfo()
const title = ref("Hello")
</script>