vue項目中使用window的onresize事件方式
vue項目使用window的onresize事件
vue項目中使用vue-echars繪制圖表時,需要實時根據(jù)窗口大小調(diào)整圖表的大小,我使用的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() { /*窗口自適應(yīng),關(guān)鍵代碼*/ window.onresize = () => { this.$refs.chart1.resize(); }; }, //注銷window.onresize事件 destroyed() { window.onresize = null; } }
注意
1、window.onresize事件一般放在created或者mounted生命周期中。
2、window.onresize中的this指向的是window,不是指向vue,如果需要調(diào)用methods中的函數(shù),需要在window.onresize事件的前面把指向vue的this賦值給其他字符,比如"_this";或者使用箭頭函數(shù)。
3、由于window.onresize是全局事件,在其他頁面改變界面時也會執(zhí)行,這樣可能會出現(xiàn)問題,需要在出這個界面時注銷window.onresize事件。
4、window.onresize說明一個問題:beforeCreate、created、beforeMount、mounted、beforeUpdate、updated中的會觸發(fā)瀏覽器事件需要在destroyed、beforeDestory中銷毀掉。
vue中window.onresize的使用
重點:
window.onresize只能在一個組件中使用,如果多個組件調(diào)用則會出現(xiàn)覆蓋情況,所以我的解決方案是在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代碼(此處進(jìn)行模塊化開發(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) } },
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue3網(wǎng)絡(luò)請求添加loading過程
這篇文章主要介紹了vue3網(wǎng)絡(luò)請求添加loading過程,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08Vue?3?表單與后端數(shù)據(jù)交互之查詢并回顯數(shù)據(jù)步驟流程
本文給大家介紹Vue3表單與后端數(shù)據(jù)交互之查詢并回顯數(shù)據(jù)步驟流程,結(jié)合實例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-12-12vue插件draggable實現(xiàn)拖拽移動圖片順序
這篇文章主要為大家詳細(xì)介紹了vue插件draggable實現(xiàn)拖拽移動圖片順序,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-12-12關(guān)于Vue中echarts響應(yīng)式頁面變化resize()的用法介紹
Vue項目中開發(fā)數(shù)據(jù)大屏,使用echarts圖表根據(jù)不同尺寸的屏幕進(jìn)行適配,resize()可以調(diào)用echarts中內(nèi)置的resize函數(shù)進(jìn)行自適應(yīng)縮放,本文將給大家詳細(xì)介紹resize()的用法,需要的朋友可以參考下2023-06-06