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

Vue预算计算器应用动态路由传参及数据渲染问题求助

Let's break down and fix your issues step by step—first, the core problem is that your User component isn't fetching the correct user data when the dynamic route changes, plus there's a bug in your toggleActive method that's preventing the active user state from working properly.

1. Fix the toggleActive Method (Critical Bug!)

Looking at your toggleActive code, you have a deadly loop here:

for (let i = 0; i < usersArr.length; usersArr++) {

You're incrementing usersArr instead of i—this will run forever and crash your app. Let's replace this with a cleaner approach using Vuex mutations (since we're dealing with state):

First, add these mutations to your Vuex store:

mutations: {
  // Reset all users to inactive
  SET_ALL_INACTIVE(state) {
    state.users.forEach(user => user.active = false);
  },
  // Set a specific user to active
  SET_USER_ACTIVE(state, userId) {
    // If using index as userId (current setup):
    state.users[userId].active = true;
    // If you add unique IDs later (recommended):
    // const user = state.users.find(u => u.id === userId);
    // if (user) user.active = true;
  }
}

Then update the toggleActive method in Navigation.vue:

toggleActive(userName) {
  // First, mark all users as inactive
  this.$store.commit('SET_ALL_INACTIVE');
  // Find the index of the user to activate
  const userIndex = this.users.findIndex(user => user.userName === userName);
  if (userIndex !== -1) {
    this.$store.commit('SET_USER_ACTIVE', userIndex);
  }
}

2. Fix Dynamic Route Linking in Navigation.vue

Your router-link structure is a bit off (you shouldn't wrap <li> inside <router-link>—it's the other way around). Also, let's add active state styling:

<ul class="navbar-nav">
  <li class="nav-item">
    <router-link class="nav-link" to="/">Home</router-link>
  </li>
  <!-- Updated user links -->
  <li 
    v-for="(user, index) in users" 
    :key="user.userName" 
    class="nav-item"
  >
    <router-link 
      class="nav-link"
      :class="{ active: user.active }" <!-- Highlight active user -->
      :to="{ name: 'User', params: { userId: index }}"
      @click="toggleActive(user.userName)"
    >
      {{ user.userName }}
    </router-link>
  </li>
</ul>

This ensures proper Bootstrap navbar structure and shows which user is currently active.

3. Make User.vue Fetch the Correct User Data

Right now, your User component expects props like userName and salary, but your route only passes userId. Let's fix this by fetching the user from Vuex using the route parameter:

Update User.vue:

<template>
  <div v-if="currentUser">
    <!-- Pass the full user object to child components -->
    <UserInfo :user="currentUser" />
    <UserIncExp :user="currentUser" />
  </div>
  <div v-else>User not found!</div>
</template>

<script>
import { mapState } from 'vuex';
import UserInfo from '../User/UserInfo.vue';
import UserIncExp from '../User/UserIncExp/_UserIncExp.vue';

export default {
  components: { UserInfo, UserIncExp },
  props: {
    userId: { 
      type: String, 
      required: true 
    }
  },
  computed: {
    ...mapState(['users']),
    currentUser() {
      // Convert userId string to number (since route params are strings)
      const userIdNum = parseInt(this.userId);
      // Return the matching user from Vuex state
      return this.users[userIdNum];
      // If you switch to unique IDs later, use this instead:
      // return this.users.find(user => user.id === this.userId);
    }
  },
  watch: {
    // Watch for route changes to refresh the user data
    '$route.params.userId'() {
      // Computed properties will auto-update, but you can add logic here if needed
    }
  }
};
</script>

Then update your child components (UserInfo and UserIncExp) to accept a user prop instead of individual fields. For example, in UserInfo.vue:

<template>
  <div>
    <h2>{{ user.userName }}</h2>
    <p>Salary: ${{ user.salary }}</p>
    <p>Leftover: ${{ user.leftover }}</p>
  </div>
</template>

<script>
export default {
  props: {
    user: {
      type: Object,
      required: true
    }
  }
};
</script>

Using array indexes as userId is fragile—if you delete a user, all subsequent indexes will shift, breaking your routes. Instead, add a unique ID when creating users:

// In your Vuex mutation for adding users
ADD_USER(state, newUser) {
  state.users.push({
    id: Date.now().toString(), // Use a timestamp or UUID library for uniqueness
    userName: newUser.userName,
    salary: newUser.salary,
    leftover: 0,
    inc: [],
    exp: [],
    active: false,
  });
}

Then update your route links to use user.id instead of index, and adjust the currentUser computed property in User.vue to find users by id.

Final Checks

  • Make sure your route config has props: true for the User route (you already do this, good job!)
  • Test switching between users—you should see the User component load the correct user's data, and the active user should be highlighted in the navbar.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 00:42:44