使用 vuejs 设置反应式屏幕宽度

Set reactive screen width with vuejs

是否可以在变量或数据 属性 跟踪 window 调整大小

时具有反应式 window 宽度

例如

computed:{
    smallScreen(){
        if(window.innerWidth < 720){
            this.$set(this.screen_size, "width", window.innerWidth)
            return true
        }
    return false
}

我不认为有办法做到这一点,除非你在 window 上附加一个监听器。 您可以在组件的 data 上添加一个 属性 windowWidth 并附加在组件安装时修改值的调整大小监听器。

尝试这样的事情:

<template>
    <p>Resize me! Current width is: {{ windowWidth }}</p>
</template

<script>
    export default {
        data() {
            return {
                windowWidth: window.innerWidth
            }
        },
        mounted() {
            window.onresize = () => {
                this.windowWidth = window.innerWidth
            }
        }
    }
</script>

希望对您有所帮助!

您还可以附加一个 class 取决于 window 宽度

<template>
    <p :class="[`${windowWidth > 769 && windowWidth <= 1024 ? 'special__class':'normal__class'}`]">Resize me! Current width is: {{ windowWidth }}</p>
</template>

<script>
export default {
    data() {
        return {
            windowWidth: window.innerWidth
        }
    },
    mounted() {
        window.onresize = () => {
            this.windowWidth = window.innerWidth
        }
    }
}
</script>

<style scoped>
.normal__class{
}
.special__class{
}
</style>

如果您在此解决方案中使用多个组件,则已接受答案的调整大小处理函数将仅更新最后一个组件。

那你应该改用这个:

import { Component, Vue } from 'vue-property-decorator';

@Component
export class WidthWatcher extends Vue {
   public windowWidth: number = window.innerWidth;

   public mounted() {
       window.addEventListener('resize', this.handleResize);
   }

   public handleResize() {
       this.windowWidth = window.innerWidth;
   }

   public beforeDestroy() {
       window.removeEventListener('resize', this.handleResize);
   }
}

来源:https://github.com/vuejs/vue/issues/1915#issuecomment-159334432