0
点赞
收藏
分享

微信扫一扫

【vue】当窗口改变时如何强制刷新组件

得一道人 2022-02-14 阅读 74

我们假定component为我们需要刷新的组件

<component :key="key"></component>

实现的核心思路是:用window.onresize监听窗口的改变,通过组件key值的改变来强制刷新组件(也可以使用v-if的true和false转换来实现刷新,不过较麻烦,不推荐)
script内容如下:

  export default {
    data() {
      return {
        key: 0,
        clientWidth : 0,//窗口宽度
      }
    },
    created() {
      this.watchWidth();//组件一创建便开始监听width的变化并记录到clientWidth中
  },
  	watch: {
      clientWidth() {
        this.key++;//当窗口宽度变化时,增加key值,从而刷新dom
    },
  },
    methods: {      
      watchWidth() {//监听窗口的宽度,一旦窗口变化,就记录clientwidth
        const that = this;//保证指向Vue而不是window
        window.onresize = function () {
          that.clientWidth = document.documentElement.clientWidth;
      };
    },
    }
  }
举报

相关推荐

0 条评论