方式一:
const getList = async() => {// console.log(777721)// loading.value = true;try {const res = await getnewsList()if (res && res.data) {console.log(777722,res.data)// 更新newList的值newList.value = res.data.titlelist}} catch(e) {// console.log(777727,e)// loading.value = false;console.error('Request error:', e);}}
方式二:
async function getList() {try {// 使用 await 直接等待 getnewsList 的结果,确保逻辑清晰const res = await getnewsList();if (res && res.data) {console.log(777724,res.data)newList.value = res.data.titlelist}const res2 = await getnewsList();if (res2 && res2.data) {console.log(777725,res2.data)}} catch (error) {console.error('Request error:', error); // 捕获错误}}
方式二:
function callSideList() {callAskRecordList().then((res) => { // 成功请求后处理结果if (res && res.data) { // 判断 res 和其中的数据是否存在leftList.value = res.data; // 将获取到的数据赋值给 leftList}}).catch((error) => { // 捕获并处理请求错误console.error('Request error:', error);});}
开始挂载:
onMounted(async () => {// getList()console.log(777741)// await tabTitle();// 在获取数据后调用 newList 函数await getList();// 默认选中第一个类别tabif (categories.value.length > 0) {currentCategory.value = categories.value[0]}});
T 和 any
泛型 T 和 任意类型 any。上文中有使用到泛型 T ,这里来介绍一下泛型 T 和任意类型 any 的使用
- T(泛型): 泛型是类型参数,用于创建可重用的函数、接口或类。在定义时并不指定具体类型,而是由调用者传入的实际类型来确定。泛型的目的是使代码更加灵活和可复用,同时保持类型安全。
例如:function identity<T>(arg: T): T {return arg;}let num = identity<number>(5); // T 被推断为 numberlet str = identity<string>("hello"); // T 被推断为 string
在这个例子中,identity 函数可以接受任意类型的参数,但在使用时类型是明确的,并且返回值会保留参数的类型。其中,<T>(arg: T): T语法含义
<T>:泛型声明(arg: T):参数类型: T:返回类型
- any(任意类型): any 是 TypeScript 中的一种类型,它表示任意类型。使用 any 时,TypeScript 不会对该变量进行类型检查,任何类型的值都可以赋给它,也可以从它那里获取任意类型的值。
例如:function identityAny(arg: any): any {return arg;}let num = identityAny(5); // 返回值类型是 anylet str = identityAny("hello"); // 返回值类型也是 any
这里,identityAny 函数可以接受任意类型的参数,但返回值类型也不确定,TypeScript 不会对此进行类型检查。
