vue项目中使用window的onresize事件方式
作者:roongyan92
vue项目使用window的onresize事件
vue项目中使用vue-echars绘制图表时,需要实时根据窗口大小调整图表的大小,我使用的auto-resize属性,没有作用,没有找出错误在哪里,使用window.onresize事件,必须销毁才不会报错哦!
代码如下:
<template>
<chart ref="chart1" :options="orgOptions"></chart>
</template>
<script>
export default {
data() {
return {
orgOptions: {}
};
},
created() {
this.orgOptions = {
xAxis: {
type: "category",
data: ""
},
yAxis: {
type: "value"
},
series: [
{
data: "",
type: "line"
}
]
};
},
mounted() {
/*窗口自适应,关键代码*/
window.onresize = () => {
this.$refs.chart1.resize();
};
},
//注销window.onresize事件
destroyed() {
window.onresize = null;
}
}注意
1、window.onresize事件一般放在created或者mounted生命周期中。
2、window.onresize中的this指向的是window,不是指向vue,如果需要调用methods中的函数,需要在window.onresize事件的前面把指向vue的this赋值给其他字符,比如"_this";或者使用箭头函数。
3、由于window.onresize是全局事件,在其他页面改变界面时也会执行,这样可能会出现问题,需要在出这个界面时注销window.onresize事件。
4、window.onresize说明一个问题:beforeCreate、created、beforeMount、mounted、beforeUpdate、updated中的会触发浏览器事件需要在destroyed、beforeDestory中销毁掉。
vue中window.onresize的使用
重点:
window.onresize只能在一个组件中使用,如果多个组件调用则会出现覆盖情况,所以我的解决方案是在App.vue中使用,获取document.documentElement.clientWidth(即浏览器宽度)存放在vuex中,别的组件只需要用computed(计算属性)将vuex的clientWidth获取,然后通过watch监听clientWidth的值,即可触发组件事件。
App.vue代码
<script>
export default {
name: 'app',
mounted () {
window.onresize = () => {
this.clientWidthResize()
}
},
methods: {
clientWidthResize () {
this.$store.commit('Tool/resizeWidth', Number(document.documentElement.clientWidth))
}
}
}
</script>store中tool.js代码(此处进行模块化开发)
export default {
namespaced: true,
state: {
clientWidth: 0
},
getters: {},
mutations: {
resizeWidth(state, clientWidth) {
state.clientWidth = clientWidth;
},
},
actions: {},
}组件使用
computed: {
clientWidth () {
return this.$store.state.Tool.clientWidth || Number(document.documentElement.clientWidth)
}
},
watch: {
clientWidth (val) {
console.log(val)
}
},总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
