a.封装绑定事件和解绑事件
/**
* @description 绑定事件 on(element, event, handler)
*/
export const on = (function () {
if (document.addEventListener) {
return function (element, event, handler) {
if (element && event && handler) {
element.addEventListener(event, handler, false)
}
}
} else {
return function (element, event, handler) {
if (element && event && handler) {
element.attachEvent('on' + event, handler)
}
}
}
})()
/**
* @description 解绑事件 off(element, event, handler)
*/
export const off = (function () {
if (document.removeEventListener) {
return function (element, event, handler) {
if (element && event) {
element.removeEventListener(event, handler, false)
}
}
} else {
return function (element, event, handler) {
if (element && event) {
element.detachEvent('on' + event, handler)
}
}
}
})()
b.在vue文件里引入刚封装的绑定和解绑(引入监听方法)
import { on, off } from '@/libs/tools'
c.在methods里添加方法,如下
<template>
<div class="bodyDiv" ref="bodyDiv">
<div class="searchDiv" ref="searchDiv">
<Form :model="formInline" inline>
</Form>
</div>
<div class="tableDiv">
<Table :columns="columns1" :data="data1" :height="bodyHeight "></Table>
</div>
</div>
</template>
<script>
import { on, off } from '@/libs/tools';
export default {
data(){
return {
formInline: {},
bodyHeight: 0,
columns1: [
{
title: 'Name',
key: 'name'
},
{
title: 'Age',
key: 'age'
},
{
title: 'Address',
key: 'address'
}
],
data1: [
{
name: 'John Brown',
age: 18,
address: 'New York No. 1 Lake Park',
date: '2016-10-03'
},
{
name: 'Jim Green',
age: 24,
address: 'London No. 1 Lake Park',
date: '2016-10-01'
},
{
name: 'Joe Black',
age: 30,
address: 'Sydney No. 1 Lake Park',
date: '2016-10-02'
},
{
name: 'Jon Snow',
age: 26,
address: 'Ottawa No. 2 Lake Park',
date: '2016-10-04'
}
]
}
},
methods: {
initPage(){
//这里调数据
},
resize(){
this.bodyHeight = this.$refs.bodyDiv.offsetHeight - this.$refs.searchDiv.offsetHeight - 20 - 10 - 20;
}
},
mounted(){
this.$nextTick(() => {
this.resize();
on(window, "resize", this.resize)
this.initPage(); //初始化页面
})
},
beforeDestroy(){
off(window, 'resize', this.resize)
}
}
</script>
<style lang="less">
.bodyDiv{
width: 100%;
height: 100%;
background: #dedede;
color: #000;
}
.searchDiv{
padding: 10px;
margin-bottom: 10px;
background: #fff;
}
.tableDiv{
background: #fff;
padding: 10px;
}
</style>
这篇博客介绍了如何在Vue应用中封装addEventListener和removeEventListener来实现事件绑定和解绑。具体场景是在组件的mounted和beforeDestroy生命周期钩子中,分别调用on和off方法来监听和移除window的resize事件,从而实现表格高度根据窗口大小动态调整的功能。此外,还展示了如何在methods中定义resize方法来计算表格的高度。
1万+

被折叠的 条评论
为什么被折叠?



