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>