useMessageList.ts 2.13 KB
/*
 * @Date: 2022-06-12 22:51:21
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2022-06-13 01:01:33
 * @FilePath: /tswj/src/composables/useMessageList.ts
 * @Description: 测试处理列表查询功能中的重复代码问题
 * 感觉复用意义不大,这么写反而很麻烦
 */
import { Ref, ref } from 'vue'
import { myCommentAPI } from '@/api/C/me'
import _ from 'lodash'
import { commentListType } from '@/@types/message/interface';
import {
  loading,
  finished,
  limit,
  offset,
  finishedTextStatus,
  emptyStatus,
} from '@/composables/variable';

// scrollList的类型是个麻烦,其他地方调用时类型不一定一样
function fn(data: [], scrollList: Ref<commentListType[]>) {
// function fn(data: [], scrollList: any) {
  // 数据全部加载完成
  if (!data.length) {
    // 加载状态结束
    finished.value = true;
  }
  scrollList.value = [...scrollList.value, ...data];
  offset.value = scrollList.value.length;
  loading.value = false;
  // 隐藏loading标识,空列表图标
  if (!scrollList.value.length) {
    finishedTextStatus.value = false;
    emptyStatus.value = true;
  } else {
    emptyStatus.value = false;
  }

  return {
    scrollList,
    finished,
    loading,
    finishedTextStatus,
    emptyStatus,
  };
}

export const useMessageList = () => {
  // 我的留言接口联调
  const scrollList = ref<commentListType[]>([]);
  let obj = {
    scrollList,
    finished,
    loading,
    finishedTextStatus,
    emptyStatus,
  };

  const onLoad = async () => {
    const { data } = await myCommentAPI({ limit: limit.value, offset: offset.value });
    data.forEach((item: { target_name: string | null | undefined; c_action: string; c_name: string; }) => {
      let arr = _.split(item.target_name, '@'); // 分割评论的动作和姓名
      item.c_action = arr[0]; // 评论动作
      item.c_name = arr[1]; // 评论姓名
    });
    // fn把重复代码抽离
    obj = fn(data, scrollList);
  }

  return {
    onLoad,
    scrollList: obj.scrollList,
    loading: obj.loading,
    finished: obj.finished,
    finishedTextStatus: obj.finishedTextStatus,
    emptyStatus: obj.emptyStatus,
  };
}