You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js中实现响应式窗口参数:window.innerWidth无响应问题解决

Fixing Vue Computed Property Not Updating On Window Resize

Hey there! I totally get why this is confusing—let's break down what's happening and how to fix it properly.

Why Your Computed Property Isn't Updating

Vue's reactive system only tracks changes to data properties that belong to the Vue instance. window.innerWidth is a native browser property, not part of your Vue instance's reactive data. That's why your calculation computed property only runs once on initialization—it has no reactive dependencies to trigger a re-run when the window resizes.

The Proper Solution: Add Reactive State + Resize Listener

The fix is to wrap the window width in a reactive data property, then update that property whenever the window resizes. Here's how to adjust your code:

var vm = new Vue({
  el: '#element',
  data() {
    return {
      // Initialize with current window width
      windowWidth: window.innerWidth
    }
  },
  computed: {
    calculation() {
      console.log(this.windowWidth);
      return this.windowWidth;
    }
  },
  mounted() {
    // Create a reusable function to update the width
    const updateWindowWidth = () => {
      this.windowWidth = window.innerWidth;
    };

    // Listen for window resize events
    window.addEventListener('resize', updateWindowWidth);

    // Clean up the listener when the component is destroyed
    // This prevents memory leaks!
    this.$once('hook:beforeDestroy', () => {
      window.removeEventListener('resize', updateWindowWidth);
    });
  }
});

What's Happening Here?

  • We add windowWidth to the data object, making it a reactive property that Vue can track.
  • The calculation computed property now depends on this.windowWidth—so whenever windowWidth changes, Vue automatically re-runs the computed property.
  • We add a resize event listener to the window in the mounted hook, which updates windowWidth every time the window size changes.
  • We use this.$once('hook:beforeDestroy') to remove the event listener when the component is destroyed—this is crucial to avoid memory leaks from orphaned event listeners.

Notes On Your Alternative Approach

Your idea of adding a resize listener in mounted and running calculations directly works, but it has a couple of downsides:

  • It mixes your calculation logic with event handling, making your code less organized.
  • Computed properties have built-in caching—if multiple parts of your template depend on the calculation, Vue will only run it once per change, which is more performant than recalculating on every resize event manually.

内容的提问来源于stack exchange,提问作者user12531597

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:04:24