1.dom元素监听事件
document.getElementById('clicker').addEventListener('click', function (e) {
alert('you clicked onVcCheck')
return false
})
eg:封装
/**
* js事件监听器函数
* @param event 监听domId
* @param type eg:'click'
* @param fn 回调函数
*/
export const elEventListener = (document, event, type, fn) => {
document.getElementById(event).addEventListener(type, fn)
}
注:
当你不带括号传递一个函数的名字时'elEventListener',你传递的是函数对象本身。
当你用圆括号传递函数时'elEventListener()',你在传递执行该函数的结果
2.按对象属性对数组进行分组
/**
* 按属性对数据分组
* @params arr 数组
* @params groupFn 过滤回调函数
*/
export const groupBy = (arr, groupFn) => {
return arr.reduce(
(grouped, obj) => ({
...grouped,
[groupFn(obj)]: [...(grouped[groupFn(obj)] || []), obj],
}),
{}
)
}
// 组件调用
import { groupBy } from '@/utils'
let people = [{ name: 'John' }, { name: 'Mac' }, { name: 'Matt' }, { name: 'Sam' }]
const groupByNameLength = groupBy(people, (preson) => preson.name.length)
console.log('groupByNameLength:>>>>', groupByNameLength)
/**
* 3:[0:{name: 'Mac'},1:{name: 'Sam'}]
* 4:[0:{name: 'John'},1:{name: 'Matt'}]
*/