vue項目中使用window的onresize事件方式
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是全局事件,在其他頁面改變界面時也會執(zhí)行,這樣可能會出現問題,需要在出這個界面時注銷window.onresize事件。
4、window.onresize說明一個問題:beforeCreate、created、beforeMount、mounted、beforeUpdate、updated中的會觸發(fā)瀏覽器事件需要在destroyed、beforeDestory中銷毀掉。
vue中window.onresize的使用
重點:
window.onresize只能在一個組件中使用,如果多個組件調用則會出現覆蓋情況,所以我的解決方案是在App.vue中使用,獲取document.documentElement.clientWidth(即瀏覽器寬度)存放在vuex中,別的組件只需要用computed(計算屬性)將vuex的clientWidth獲取,然后通過watch監(jiān)聽clientWidth的值,即可觸發(fā)組件事件。
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代碼(此處進行模塊化開發(fā))
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)
}
},總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
關于Vue中echarts響應式頁面變化resize()的用法介紹
Vue項目中開發(fā)數據大屏,使用echarts圖表根據不同尺寸的屏幕進行適配,resize()可以調用echarts中內置的resize函數進行自適應縮放,本文將給大家詳細介紹resize()的用法,需要的朋友可以參考下2023-06-06

