Vue监听屏幕宽度

2020-12-21  本文已影响0人  阿杰_96c5

Vue监听屏幕宽度

首先在data中定义要监听的属性,因为watch侦听器监听的是data中的属性,不能直接监听window

在mouted当中调用window.onresize()事件,onresize事件会在窗口或框架被调整大小时触发

最后在watch监听data中的screenWidth属性就可以了

<script scoped>
    export default {
        name: "dormInfo",
        props: {},
        components: {},
        computed: {},
        data() {
            return {
                screenWidth: document.body.clientWidth,
            }
        },
        methods: {},
        mounted() {
            const that = this
            window.onresize= () => {
                return (() => {
                    window.screenWidth = document.body.clientWidth;
                    that.screenWidth = window.screenWidth;
                })();
            }
        },
        created() {
        },
        watch: {
            /* 监听*/
            screenWidth(val) {
                    this.screenWidth = val;
                console.log("this.screenWidth",this.screenWidth)
            }
        }
    }
</script>
上一篇 下一篇

猜你喜欢

热点阅读