vue中window.onresize的使用解析
window.onresize的使用
說下重點
window.onresize只能在一個組件中使用,如果多個組件調用則會出現(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代碼(此處進行模塊化開發(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) ? } },
window.onresize筆記
1.瀏覽器尺寸變化響應事件
?window.onresize = function(){....}
這里需要注意的是,onresize響應事件處理中,獲取到的頁面尺寸參數(shù)是變更后的參數(shù)。
// 獲取到的是變更后的頁面寬度 var currentWidth = document.body.clientWidth;?
如果需要使用到變更之前的參數(shù),需要建一個全局變量保存之前的參數(shù)(并且記得在onresize事件中刷新這個全局變量保存新的參數(shù)值)。
2.谷歌瀏覽器中
window.onresize事件默認會執(zhí)行兩次(偶爾也會只執(zhí)行一次,網(wǎng)上大部分說法認為這是Chrome的bug)。
解決方法:
一般來說推薦新建一個標志位 延時復位控制它不讓它自己執(zhí)行第二次,代碼如下:
var firstOnResizeFire = true;//谷歌瀏覽器onresize事件會執(zhí)行2次,這里加個標志位控制 ? window.onresize = function() { ?if (firstOnResizeFire) { ? NfLayout.tabScrollerMenuAdjust(homePageWidth); ? firstOnResizeFire = false; ?? ? //0.5秒之后將標志位重置(Chrome的window.onresize默認執(zhí)行兩次) ? setTimeout(function() { ? ?firstOnResizeFire = true; ? ? ? ? }, 500); ?}? ?homePageWidth = document.body.clientWidth; //重新保存一下新寬度 }
3.頁面尺寸變更事件
注意要分為尺寸增大和尺寸變小兩個方向考慮。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue+uniapp瀑布流布局多種實現(xiàn)方式示例代碼
由于使用uniapp開發(fā)的微信小程序不需要考慮響應式,因此瀑布流的實現(xiàn)相對于pc端更為簡單,下面這篇文章主要給大家介紹了關于vue+uniapp瀑布流布局多種實現(xiàn)方式的相關資料,需要的朋友可以參考下2023-03-03詳解Vue一個案例引發(fā)「內容分發(fā)slot」的最全總結
這篇文章主要介紹了詳解Vue一個案例引發(fā)「內容分發(fā)slot」的最全總結,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12拖拽插件sortable.js實現(xiàn)el-table表格拖拽效果
本文主要介紹了拖拽插件sortable.js實現(xiàn)el-table表格拖拽效果,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02