vue 通过vuex与window.onresize事件 全局监听窗口的变化

实现原理

1,通过引用外部js 全局使用一个window.onresize事件(多个会被覆盖),并通过vue实例化 向vuex中存储数据,
2,通过watch 监听vuex 中数据的变化,从而实现自适应等需求。

main.js


// Window.onresize 事件  动态调整窗口
import "@/assets/js/onresize";

var vue = new Vue({
    
    
  router,
  store,
  render: h => h(App),
  components:{
    
    
    App  
   }
}).$mount('#app')
export default vue

外部js onresize.js

import _this from '../../main.js'


// 设置 init 函数
function init () {
    
    
  if(_this){
    
    
    let innerWH = {
    
    
        innerWidth:window.innerWidth,
        innerHeight:window.innerHeight,
    }
  _this.$store.commit('setInnerWH',innerWH);
  console.log(' window.innerWidth', window.innerWidth);
  console.log(' window.innerHeight', window.innerHeight);
 
  }
}

// 节流 ms 触发间隔毫秒
var ms= 300;
var lastClick = Date.now() - ms;
// 初始化
init();
// 改变窗口大小时重新设置 rem
window.onresize = function () {
    
    
  // 节流 
  if (Date.now() - lastClick >= ms) {
    
    
    init();
    lastClick = Date.now();
  }
}

vuex

	   innerWH:{
    
    
	      innerWidth:'1',
	      innerHeight:'',
	    
	  },

  
    setInnerWH(state,{
    
    innerWidth,innerHeight}){
    
    
      state.innerWH.innerWidth= innerWidth;
      state.innerWH.innerHeight= innerHeight;
    },

组件中监听vuex

  watch: {
    
    
    "$store.state.innerWH": {
    
    
      handler() {
    
    
        this.autoScroll();
        this.prevent();
        console.log("监听", this.$store.state.innerWH);
      },
      deep: true,
      //监听vuex中userName变化而改变header里面的值
    },
  },

猜你喜欢

转载自blog.csdn.net/weixin_43245095/article/details/109466713