方式一:

  1. const getList = async() => {
  2. // console.log(777721)
  3. // loading.value = true;
  4. try {
  5. const res = await getnewsList()
  6. if (res && res.data) {
  7. console.log(777722,res.data)
  8. // 更新newList的值
  9. newList.value = res.data.titlelist
  10. }
  11. } catch(e) {
  12. // console.log(777727,e)
  13. // loading.value = false;
  14. console.error('Request error:', e);
  15. }
  16. }

方式二:

  1. async function getList() {
  2. try {
  3. // 使用 await 直接等待 getnewsList 的结果,确保逻辑清晰
  4. const res = await getnewsList();
  5. if (res && res.data) {
  6. console.log(777724,res.data)
  7. newList.value = res.data.titlelist
  8. }
  9. const res2 = await getnewsList();
  10. if (res2 && res2.data) {
  11. console.log(777725,res2.data)
  12. }
  13. } catch (error) {
  14. console.error('Request error:', error); // 捕获错误
  15. }
  16. }

方式二:

  1. function callSideList() {
  2. callAskRecordList()
  3. .then((res) => { // 成功请求后处理结果
  4. if (res && res.data) { // 判断 res 和其中的数据是否存在
  5. leftList.value = res.data; // 将获取到的数据赋值给 leftList
  6. }
  7. })
  8. .catch((error) => { // 捕获并处理请求错误
  9. console.error('Request error:', error);
  10. });
  11. }

开始挂载:

  1. onMounted(async () => {
  2. // getList()
  3. console.log(777741)
  4. // await tabTitle();
  5. // 在获取数据后调用 newList 函数
  6. await getList();
  7. // 默认选中第一个类别tab
  8. if (categories.value.length > 0) {
  9. currentCategory.value = categories.value[0]
  10. }
  11. });

T 和 any

泛型 T 和 任意类型 any。上文中有使用到泛型 T ,这里来介绍一下泛型 T 和任意类型 any 的使用

  1. T(泛型): 泛型是类型参数,用于创建可重用的函数、接口或类。在定义时并不指定具体类型,而是由调用者传入的实际类型来确定。泛型的目的是使代码更加灵活和可复用,同时保持类型安全。
  1. 例如:
  2. function identity<T>(arg: T): T {
  3. return arg;
  4. }
  5. let num = identity<number>(5); // T 被推断为 number
  6. let str = identity<string>("hello"); // T 被推断为 string

在这个例子中,identity 函数可以接受任意类型的参数,但在使用时类型是明确的,并且返回值会保留参数的类型。其中,<T>(arg: T): T语法含义

  1. <T>:泛型声明
  2. (arg: T):参数类型
  3. : T:返回类型
  1. any(任意类型): any 是 TypeScript 中的一种类型,它表示任意类型。使用 any 时,TypeScript 不会对该变量进行类型检查,任何类型的值都可以赋给它,也可以从它那里获取任意类型的值。
  1. 例如:
  2. function identityAny(arg: any): any {
  3. return arg;
  4. }
  5. let num = identityAny(5); // 返回值类型是 any
  6. let str = identityAny("hello"); // 返回值类型也是 any

这里,identityAny 函数可以接受任意类型的参数,但返回值类型也不确定,TypeScript 不会对此进行类型检查。