Vue.js中实现响应式窗口参数:window.innerWidth无响应问题解决
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
windowWidthto thedataobject, making it a reactive property that Vue can track. - The
calculationcomputed property now depends onthis.windowWidth—so wheneverwindowWidthchanges, Vue automatically re-runs the computed property. - We add a
resizeevent listener to the window in themountedhook, which updateswindowWidthevery 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

