Vue中使用Lodash

Vue2中使用 

安装

npm i -S lodash

全局引入

import _ from 'lodash'
Vue.prototype._ = _

使用

在任何地方使用_或者this._即可调用lodash

对象数组排序

    let users = [
      { user: 'a', age: 48 },
      { user: 'b', age: 34 },
      { user: 'a', age: 42 },
      { user: 'b', age: 55 }
    ];

    let c = this._.orderBy(users, ['age'], ['desc']);
    console.log('age降序排列:', c);

    let d = _.orderBy(users, ['user', 'age'], ['desc', 'asc']);
    console.log('user降序,age升序排序:', d);

场景1:

我们要可视化今天各个小时的数据,其中x轴为

 ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15'],但是后端返回的json数据中缺失了某个时间段的数据,为了不让echart中时间段错位,我们需要补上这一条数据,其值设置为0

 封装函数:

 

    test(
      arr1 = ['00', '01', '02', '03'],
      arr2 = [
        { value: '12', name: '00' },
        { value: '45', name: '01' },
        { value: '65', name: '03' }
      ],
      orderKey = 'name',
      order = 'asc'
    ) {
      let arr_result = arr2.map((d) => d.name);
      let a = arr1.filter((item) => !arr_result.includes(item));
      if (a.length !== 0) {
        a.forEach((item) => {
          arr2.push({ value: '0', name: item });
        });
      }
      return _.orderBy(arr2, [orderKey], [order]);
    },

下面是一个示例,说明如何根据每个对象中的嵌套属性进行排序:

const items = [
  {
    id: 1,
    entry: 'a',
    nested: { val: 5 },
  },
  {
    id: 5,
    entry: 'five',
    nested: { val: 1 },
  },
  {
    id: 3,
    entry: 'three',
    nested: { val: 2 },
  },
  {
    id: 2,
    entry: 'two',
    nested: { val: 3 },
  },
  {
    id: 4,
    entry: 'four',
    nested: { val: 4 },
  },
];


const nestedValueComparator = item => _.get(item, 'nested.val');

const nestedData = _.orderBy(items, nestedValueComparator, ['asc']);

Vue3中使用

安装:

npm i -S lodash-es

引入:

import { debounce } from 'lodash-es';

使用防抖函数:

  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值