vue实时获取页面宽高(js和vue插件)

方法一: js

export default {
    data(){
        return{
            windowWidth: document.documentElement.clientWidth,  //实时屏幕宽度
            windowHeight: document.documentElement.clientHeight,   //实时屏幕高度
        }
    },    
    // 
    watch: {
      windowHeight (val) {
        let that = this;
        console.log("实时屏幕高度:",val, that.windowHeight );
      },
      windowWidth (val) {
        let that = this;
        console.log("实时屏幕宽度:",val, that.windowHeight );
      }
    },

    mounted() {
        var that = this;
        // 
        window.onresize = () => {
            return (() => {
              window.fullHeight = document.documentElement.clientHeight;
                window.fullWidth = document.documentElement.clientWidth;
              that.windowHeight = window.fullHeight;  // 高
              that.windowWidth = window.fullWidth; // 宽
            })()
          };
    },
}

方法二:

使用vue插件  element-resize-detector

 第一步:安装

安装命令  npm install --save element-resize-detector

卸载命令  npm uninstall element-resize-detector

第二步:引入

第三步:使用

export default {
    data(){
        return{
            windowHeight:null,
            windowWidth:null,

    },
    mounted() {
      const that = this;
      var erd = elementResizeDetector();
      erd.listenTo('监听的dom', (element) => {   //监听的domdocument.get方法获取
        that.windowWidth= element.offsetWidth;
        that.windowHeight= element.offsetHeight;
        that.$nextTick(() => { 
            console.log("宽:"+that.windowWidth,"高:"+that.windowHeight)
            // 这里填写监听改变后的操作
        });
      });
    },
    



}



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