Vue监听窗口变化

2019/10/25 posted in  Vue
Tags:  #vue

需求

响应窗口变化做一些事情

实现

// 1. 在mounted钩子中创建监听事件
mounted() {
    // 监听窗口宽度变化
    window.onresize = () => {
      this.$store.commit(
        "SETCLIENTWIDTH",
        document.documentElement.clientWidth
      );
    };
}
// 2. 存储视口信息(本次项目使用的是vuex,非必须)
SETCLIENTWIDTH(state, width) {
    state.clientWidth = width
},
// 3. 监听视口信息变化
computed: {
    clientWidth() {
      return this.$store.state.clientWidth;
    }
}
// 4. 根据变化做相应操作
...

只提供大体思路,根据实际情况可做变动

« Vue路由相关的坑 Js获取当前日期时间及其它操作 »