前端使用vue动态的获取当前窗口宽高大小并实时保存 编写不同端页面常用

可以动态的获取当前窗口的大小,用于编写多端的时候常用

winsize (主要获取页面宽高代码)

import store from "@/store";

const { body } = document
const WIDTH = 992

export default {
    # 监听 只要有变化就调用resizeHandler函数
    beforeMount(){
        window.addEventListener('resize', this.resizeHandler)
    },
    # 卸载
    beforeDestroy() {
        window.removeEventListener('resize', this.resizeHandler)
    },
    # 第一次进入页面时主动调用该函数
    mounted() {
        this.resizeHandler()
    },

    methods: {
      resizeHandler(){
          # 获取宽高
          const rect = body.getBoundingClientRect()
          let winSize = {
              height: rect.height,
              width: rect.width
          }
          # 传入到vue的app仓库里面去保存数据
          store.dispatch("app/setWinSize", winSize)
          # 打印宽高
          console.log(winSize)
      }
    }
}

app仓库(存放我们获取的页面宽和高)

const state = {
    winSize: {
        height: 1080,
        width: 1920
    }
}

const mutations = {
    SET_WIN_SIZE: (state, size) => {
        state.winSize = size
    }
}

const actions = {
    setWinSize({ commit }, size) {
        commit('SET_WIN_SIZE', size)
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}

你可能感兴趣的:(vue.js,前端,javascript)