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

Vue.js中列表无法动态显示的问题求助

解决Vuex数据首次加载不渲染的问题

Hey there! Let's break down why your list isn't showing up on the first page load and fix it right away.

问题根源

The core issue here is how you're handling the heures property in your component:

  • When your component initializes, you set heures to this.$store.getters.getJourneeList once in the data() function. At this point, your async API call in the Vuex action hasn't finished yet—so the store's journees is still an empty object.
  • After the API call completes and updates the store, the heures property in data() doesn't automatically sync with the new store data. Vue's data properties only set up reactive bindings during initialization; they don't track external state changes like Vuex getters afterward.
  • When you switch routes and come back, the component re-mounts. By this time, the store already has the fetched data, so heures gets the populated list on initialization, which is why it shows up then.

修复方案

The simplest and most Vue-idiomatic fix is to use a computed property instead of a data property for heures. Computed properties automatically react to changes in their dependencies (like your Vuex getter).

修改组件代码

Replace your component's <script> section with this:

<script>
export default {
  name: "TimeList",
  // Remove the data property for heures, add a computed property instead
  computed: {
    heures() {
      return this.$store.getters.getJourneeList;
    }
  },
  created() {
    this.$store.dispatch('getJourneesUser');
  }
}
</script>

额外优化建议

  • In your Vuex module, change the initial state of journees from an empty object {} to an empty array []:
    const state = {
      journees: [], // Use array instead of object for list data
    };
    
    This makes more sense because you're rendering a list with v-for—iterating over an empty array will just show nothing, whereas iterating over an empty object could lead to unexpected behavior (like trying to render object keys).

为什么这样有效

Computed properties in Vue are reactive—they automatically re-calculate whenever their dependent values change. When your Vuex action finishes fetching data and updates the journees state, the getJourneeList getter returns the new data, and your heures computed property updates immediately. This triggers the template to re-render, showing your list on the first load without needing to switch routes.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 14:12:44