vue中使用lodash小工具

lodash

百度词条对lodash的解释:一个 JavaScript 的实用工具库, 表现一致性, 模块化, 高性能, 以及 可扩展。内涵大量的处理函数,具体有哪些可以查看Lodash 中文文档,现在我们来看一下其在vue项目中的使用,这里我用几个小案例来呈现。

安装
npm i --save lodash
引入
/* 示例一 */
import debounce from "lodash/debounce"; //debounce防抖操作
//当然也可以全局导入
//import _ from 'lodash'
//_.debounce 的方式调用
/* 示例二 */
import findLast from "lodash/findLast"; //从右至左遍历collection (集合)元素的。
使用
/* 示例一 */
export default {
  props: {
    option: {
      type: Object,
      default: () => {}
    }
  },
  watch: {
    option(val) {
      this.chart.setOption(val);
    }
    // options: { //深度监听(极消耗性能)
    //   handler(val) {
    //     this.chart.setOption(val);
    //   },
    //   deep: type
    // }
  },
  created() {
    this.resize = debounce(this.resize, 300);
  },
  mounted() {
    this.renderChart();
    addListener(this.$refs.chartDom, this.resize);
  },
  beforeDestroy() {
    removeListener(this.$refs.chartDom, this.resize); //关闭监听事件
    this.chart.dispose(); //清理第三方库,防止内存泄漏
    this.chart = null;
  },
  methods: {
    resize() {
      console.log("debounce");
      this.chart.resize();
    },
    renderChart() {
      this.chart = echarts.init(this.$refs.chartDom);
      this.chart.setOption(this.option);
    }
  }
};
/* 示例二 */
router.beforeEach((to, from, next) => {
  if (to.path != from.path) {
    NProgress.start();
  }

  const record = findLast(to.matched, record => record.meta.author);  //遍历路由,返回路由中meta标记的author值
  if (record && !check(record.meta.author)) {  
    if (!isLogin() && to.path != "/user/login") {
      next({
        path: "/user/login"
      });
    } else if (to.path != "/403") {
      Notification['error']({
        message: '403',
        description: '请联系管理员增加权限',
      });
      next({
        path: "/403"
      });
    }
    NProgress.done();
  }
  next();
});

router.afterEach(() => {
  NProgress.done();
});
参数解释
_.debounce(func, [wait=0], [options={}])
func --> 需要防抖的函数
wait --> 延迟 wait 毫秒后调用 func 方法
[options={}] (Object): 选项对象。
[options.leading=false] (boolean): 指定在延迟开始前调用。
[options.maxWait] (number): 设置 func 允许被延迟的最大值。
[options.trailing=true] (boolean): 指定在延迟结束后调用。

_.findLast(collection, [predicate=_.identity], [fromIndex=collection.length-1])
collection (Array|Object): 一个用来迭代的集合。
[predicate=_.identity] (Array|Function|Object|string): 每次迭代调用的函数。
[fromIndex=collection.length-1] (number): 开始搜索的索引位置

常用方法

  • chunk 数组切分
  • compact 过滤所有的空值,0,NaN
  • uniq 数组去重
  • merge 参数合并
  • extend 类似参数对象合并
  • keys 取出对象中所有的key值组成数组
  • debounce 防抖
  • throttle 节流
  • difference 从数组中过滤元素
  • drop 从数组中删除元素
  • pull 移除数组中指定值(直接操作原数组)
  • join 指定字符拼接数组为字符串
  • last 获取数组最后一个元素
  • random 随机数
  • isEmpty 检查空数组或者空对象
  • cloneDeep 深拷贝
  • clone 复制
  • get 获取对象指定路径对应的值
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值