Vue.js中列表无法动态显示的问题求助
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
heurestothis.$store.getters.getJourneeListonce in thedata()function. At this point, your async API call in the Vuex action hasn't finished yet—so the store'sjourneesis still an empty object. - After the API call completes and updates the store, the
heuresproperty indata()doesn't automatically sync with the new store data. Vue'sdataproperties 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
heuresgets 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
journeesfrom an empty object{}to an empty array[]:
This makes more sense because you're rendering a list withconst state = { journees: [], // Use array instead of object for list data };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

