Javascript Vue JS - 如何在更改时获取窗口大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49380830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:21:57  来源:igfitidea点击:

Vue JS - How to get window size whenever it changes

javascripthtmlvue.js

提问by sara

I'm new to vuejs but I was trying to get the window size whenever I resize it so that i can compare it to some value for a function that I need to apply depending on the screen size. I also tried using the watch property but not sure how to handle it so that's probably why it didn't work

我是 vuejs 的新手,但是每当我调整它的大小时,我都试图获取窗口大小,以便我可以将它与我需要根据屏幕大小应用的函数的某个值进行比较。我也尝试使用 watch 属性,但不确定如何处理它,所以这可能是它不起作用的原因

  methods: {

    elem() {
     this.size = window.innerWidth;
     return this.size;
   },
  mounted() {
    if (this.elem < 767){ //some code }
   }

回答by Goran

Put this code inside your Vue component:

将此代码放在您的 Vue 组件中:

created() {
  window.addEventListener("resize", this.myEventHandler);
},
destroyed() {
  window.removeEventListener("resize", this.myEventHandler);
},
methods: {
  myEventHandler(e) {
    // your code for handling resize...
  }
}

This will register your Vue method on component creation, trigger myEventHandler when the browser window is resized, and free up memory once your component is destroyed.

这将在组件创建时注册您的 Vue 方法,在调整浏览器窗口大小时触发 myEventHandler,并在您的组件被销毁后释放内存。

回答by Calvintwr

Simplest approach

最简单的方法

https://www.npmjs.com/package/vue-window-size

https://www.npmjs.com/package/vue-window-size

Preview

预览

import Vue from 'vue';
import VueWindowSize from 'vue-window-size';

Vue.use(VueWindowSize);

You would then access it normally from your components like this:

然后您可以像这样从您的组件正常访问它:

<template>
  <div>
    <p>window width: {{ windowWidth }}</p>
    <p>window height: {{ windowHeight }}</p>
  </div>
</template>

回答by Gayan Sandamal

You can use this anywhere anytime

您可以随时随地使用它

methods: {
    //define below method first.
    winWidth: function () {
        setInterval(() => {
            var w = window.innerWidth;
            if (w < 768) {
                this.clientsTestimonialsPages = 1
            } else if (w < 960) {
                this.clientsTestimonialsPages = 2
            } else if (w < 1200) {
                this.clientsTestimonialsPages = 3
            } else {
                this.clientsTestimonialsPages = 4
            }
        }, 100);
    }
},
mounted() {
    //callback once mounted
    this.winWidth()
}