vue使用lodash

作者: 菲鸽 | 来源:发表于2018-08-17 20:44 被阅读0次

一、安装

cnpm i lodash -S

二、方法一

1、引入

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

2、使用

this._.debounce(this.handleClick,1000,false)

二、方法二

1、引入

let _ = require('lodash')

2、使用

_.debounce(this.handleClick,1000,false)

三、vue单文件组件中使用

里面分别有我自己写的debounce函数和lodash的debounce函数,效果一样!

<template>
  <div>
    <el-button @click="myDebounce">我的debounce</el-button>
    <el-button @click="_debounce">lodash的debounce</el-button>
  </div>
</template>

<script>
import { debounce } from '@/utils/util'
let _ = require('lodash')
export default {
  methods: {
    handleClick1() {
      console.log(`真正执行的函数,次数比较少:handleClick1.....`)
    },
    handleClick2() {
      console.log(`真正执行的函数,次数比较少:handleClick2.....`)
    },
    myDebounce() {
      console.log(`myDebounce.....`)
      this.DB()
    },
    _debounce() {
      console.log(`_debounce.....`)
       this._DB()
    }
  },
  created() {
    this.DB = debounce(this.handleClick1, 1000, false)
    this._DB = this._.debounce(this.handleClick2,1000,false)
  }
}
</script>
debounce测试.png
注意:以前我是在data选项里面定义DB:null,然后再methods里面初始化函数,但是需要判断‘如果有了就不赋函数,如果为空就赋’,发现比较麻烦;后来直接在created钩子里面定义,就很方便了!

相关文章

网友评论

    本文标题:vue使用lodash

    本文链接:https://www.haomeiwen.com/subject/fmntiftx.html