Vue & LoDash:激活标签切换功能失效问题排查
Hey there! Let's break down why your tab switching isn't working as expected and fix it up.
The Core Problem
Looking at your code, the issue likely boils down to Vue's reactivity system not picking up the changes when you modify the is_active properties via LoDash's _.forEach. Even though Vue should track changes to object properties, batch updates like this can sometimes slip through the cracks (especially in Vue 2). Alternatively, if your auctions array isn't properly reactive (like if it's frozen or wasn't initialized correctly), the DOM won't update when you toggle the is_active flag.
Fix 1: Trigger Reactivity by Replacing the Array
The most reliable way to make Vue notice the changes is to create a new copy of the array, update the properties, and then reassign it. This forces Vue to detect the array change and refresh the DOM:
toggleTab(idx) { // Create a new array with all tabs set to inactive const updatedAuctions = this.auctions.map(auction => ({ ...auction, // Copy all existing properties is_active: false })); // Set the clicked tab to active updatedAuctions[idx].is_active = true; // Reassign the array to trigger reactivity this.auctions = updatedAuctions; }
Fix 2: Ensure Property Changes Are Tracked (Vue 2 Specific)
If you want to keep using LoDash and avoid creating a new array, use Vue's $set method to update the is_active property. This guarantees that Vue's reactivity system picks up the change:
toggleTab(idx) { _.forEach(this.auctions, (_, index) => { // Use $set to update the property reactively this.$set(this.auctions[index], 'is_active', false); }); // Activate the selected tab this.$set(this.auctions[idx], 'is_active', true); }
Fix 3: Ditch LoDash for Native Array Methods
You don't even need LoDash here! Native array methods work just fine and avoid any potential compatibility quirks:
toggleTab(idx) { // Use native forEach to set all tabs to inactive this.auctions.forEach(auction => { auction.is_active = false; }); // Activate the clicked tab this.auctions[idx].is_active = true; }
If this still doesn't work, double-check that your auctions array is initialized in Vue's data option (so it's reactive) and that no other code is overriding the is_active properties. Also, check the browser console for any errors (like index out of bounds) that might be breaking the function.
内容的提问来源于stack exchange,提问作者jgravois

