【Vue2】一个数组按时间分割为【今年】和【往年】俩个数组

一. 需求

后端返回一个数组,前端按时间维度将该数组的分割为【今年】和【往年】俩个数组
  1. 后端返回的数组格式如下
bash 复制代码
timeList:[
	{id:1,billTime:"2024-01-10",createTime:"2024-01-10 00:00:00",status:0},
	{id:2,billTime:"2022-05-25",createTime:"2022-05-25 00:00:00",status:1},
	{id:3,billTime:"2022-03-23",createTime:"2022-03-23 00:00:00",status:2},
	{id:4,billTime:"2022-02-11",createTime:"2022-02-11 00:00:00",status:0},
	{id:5,billTime:"2022-01-01",createTime:"2022-01-01 00:00:00",status:2},
	{id:6,billTime:"2021-12-01",createTime:"2021-12-01 00:00:00",status:2},
	{id:7,billTime:"2021-11-01",createTime:"2021-11-01 00:00:00",status:2},
]
  1. 需要的数组如下
bash 复制代码
// 往年
preYear:[
	{billTime:"2022-05",value:"2022-05"},
	{billTime:"2022-03",value:"2022-03"},
	{billTime:"2022-02",value:"2022-02"},
	{billTime:"2022-01",value:"2022-01"},
	{billTime:"2021-12",value:"2021-12"},
	{billTime:"2021-11",value:"2021-11"},
]
// 今年
newYear:[
	{billTime:"2024-01",value:"2024-01"},
]
  1. 效果如下
    全部账期【今年账期】(点击切换标签)、往年账期(下拉框)

二. 实现

bash 复制代码
<template>
	<div>
		<!-- 本年账期 -->
		<el-radio-group v-model="newTime" @change="handleChangeNewTime" size="mini">
			<el-radio-button v-for="(item,index) in newYear" :key="index" :label="item.billTime" :value="item.value">
				<template>
					<span>{{item.value}}</span>
				</template>
			</el-radio-button>
		</el-radio-group>
		<!-- 往年账期 -->
		<el-button size="mini" style="margin-left: 20px" split-button>往年账期</el-button>
		<el-select @change="billTimeSearch" v-model="preTime" size="mini" placeholder="请选择" clearable>
			<el-option v-for="(item,index) in preYear" :key="index" :label="item.billTime" :value="item.billTime">
			</el-option>
		</el-select>
	<div>
</template>

<script>
import { getBillTime,getList } from "@/api/xxx"
import { dateFormat } from "@/utils/index";

	export default{
		data(){
			return{
				query:{
					pageNum:1,
					pageSize:10,
					startTime:"" // 选中的账期
				},
				list:[],
				listLoading:false,
				newYear:[], // 本年账期列表
				preYear:[], // 往年账期列表
				preTime:"", // 选中的往年账期
				newTime:""	// 选中的今年账期
			}
		},
		mounted(){
			this.fetchData()
			this.getBillTime()
		},
		methods:{
			/**
			* 初始化列表数据
			*/
			fetchData(){
				this.listLoading = true
				getList(this.query).then(res=>{
					this.list = res.data.list
					this.listLoading = false
				})
			},

			/**
			* 获取列表,并按照时间分割为【往年】和【今年】账期
			*/
			getBillTime(){
				getBillTime().then(res=>{
					let currentYear = this.formatDateYear(new Date())
					res.data.list.forEach(item=>{
						item.billTime = this.formatDate(item.billTime)
						let obj = {billTime:item.billTime,value:item.billTime};
						if(item.billTime.indexOf(currentYear) == -1 || this.newYear.length == 12){
							this.preYear.push(obj)
							// 去重
							this.preYear = this.preYear.reduce((preVal,curVal) => {
                            	object[curVal.billTime] ? "" : (object[curVal.billTime] = preVal.push(curVal));
                            	return preVal;
                        	}, []);
						}else{
							this.newYear.push(obj);
                        	// 账单日重复问题
                        	let object = {};
                        	this.newYear = this.newYear.reduce((preVal, curVal) => {
                            	object[curVal.billTime] ? "" : (object[curVal.billTime] = preVal.push(curVal));
                            	return preVal;
                        	}, []);
						}
					});
					var result = this.newYear.some(item => {
                    	if (item.billTime == "") {
                        	return true;
                    	}
                	});
                	if (!result) {
                    	// 如果存在
                    	this.newYear.unshift({ billTime: "", value: "全部账单" });
               		}
				})
			},

			/**
         	* 切换今年账单日标签项
         	* @param {String} val 
         	*/
        	handleChangeNewTime(val) {
            	this.query.startTime = val;
            	this.preTime = ""
            	// this.$refs.orderListRef.clearSelection();
            	this.fetchData();
        	},

        	/**
         	* 往年账单筛选 此处仅需要传一个值年月即可,后端进行模糊查询
         	* @param {String} val 
         	*/
        	billTimeSearch(val) {
            	this.query.startTime = val;
            	this.newTime = ""
            	this.fetchData();
        	},

        	/**
         	* 账单日格式化
         	* @param {Date} date 
         	*/
        	formatDate(date) {
            	return dateFormat(new Date(date), "yyyy-MM");
        	},
        	formatDateYear(date) {
            	return dateFormat(new Date(date), "yyyy");
        	},
		}
	}
</script>

三. 时间转换

@/utils/index

bash 复制代码
//格式化时间
export function dateFormat(date, format) {
  format = format || "yyyy-MM-dd hh:mm:ss";
  if (date !== "Invalid Date") {
    let o = {
      "M+": date.getMonth() + 1, //month
      "d+": date.getDate(), //day
      "h+": date.getHours(), //hour
      "m+": date.getMinutes(), //minute
      "s+": date.getSeconds(), //second
      "q+": Math.floor((date.getMonth() + 3) / 3), //quarter
      S: date.getMilliseconds() //millisecond
    };
    if (/(y+)/.test(format))
      format = format.replace(
        RegExp.$1,
        (date.getFullYear() + "").substr(4 - RegExp.$1.length)
      );
    for (let k in o)
      if (new RegExp("(" + k + ")").test(format))
        format = format.replace(
          RegExp.$1,
          RegExp.$1.length === 1 ?
          o[k] :
          ("00" + o[k]).substr(("" + o[k]).length)
        );
    return format;
  }
  return "";
}
相关推荐
程序员爱技术1 小时前
Vue 2 + JavaScript + vue-count-to 集成案例
前端·javascript·vue.js
悦涵仙子2 小时前
CSS中的变量应用——:root,Sass变量,JavaScript中使用Sass变量
javascript·css·sass
兔老大的胡萝卜2 小时前
ppk谈JavaScript,悟透JavaScript,精通CSS高级Web,JavaScript DOM编程艺术,高性能JavaScript pdf
前端·javascript
cs_dn_Jie6 小时前
钉钉 H5 微应用 手机端调试
前端·javascript·vue.js·vue·钉钉
开心工作室_kaic6 小时前
ssm068海鲜自助餐厅系统+vue(论文+源码)_kaic
前端·javascript·vue.js
有梦想的刺儿7 小时前
webWorker基本用法
前端·javascript·vue.js
清灵xmf7 小时前
TypeScript 类型进阶指南
javascript·typescript·泛型·t·infer
小白学大数据8 小时前
JavaScript重定向对网络爬虫的影响及处理
开发语言·javascript·数据库·爬虫
qq_390161778 小时前
防抖函数--应用场景及示例
前端·javascript
334554328 小时前
element动态表头合并表格
开发语言·javascript·ecmascript