Firebase+Vue.js中键为数字时的数据获取方法
Hey there! Let's work through your problem step by step—numeric keys can be tricky with dot notation, but there's a straightforward fix, plus ways to dynamically access data and check for its existence.
1. Accessing Numeric/Non-Standard Keys Directly
If your stored data has a key that's a numeric string like '2018', dot notation (currentUser.2018) will throw an error because JavaScript identifiers can't start with numbers. Instead, use bracket notation with the key as a string:
{{ currentUser['2018'] }}
Looking at your save code, though, your actual keys are combined year/month strings like '2018/January'. For those, you'd use the same bracket notation with the full key string:
{{ currentUser['2018/January'] }}
This avoids the syntax restriction of dot notation and lets you access the property correctly.
2. Dynamic Access Using Variables
To fetch data based on a user-selected date (year + month), build the key string dynamically and use bracket notation with your variables. Let's say you have selectedYear (e.g., '2018') and selectedMonth (e.g., 'January') in your component:
In your template:
{{ currentUser[selectedYear + '/' + selectedMonth] }}
Or use ES6 template literals for cleaner syntax (supported in most modern frameworks):
{{ currentUser[`${selectedYear}/${selectedMonth}`] }}
This will automatically construct the correct key and retrieve the matching data.
3. Checking if the Data Exists
To verify if data exists for a selected date, use conditional checks to avoid errors from accessing undefined properties. Here are two common approaches:
Conditional in the template
<div v-if="currentUser && currentUser[`${selectedYear}/${selectedMonth}`]"> Data found: {{ currentUser[`${selectedYear}/${selectedMonth}`] }} </div> <div v-else> No data available for this date. </div>
Using a computed property (cleaner for complex logic)
In your component's script:
computed: { selectedDateData() { if (!this.currentUser) return null; const key = `${this.selectedYear}/${this.selectedMonth}`; return this.currentUser[key] || null; } }
Then in the template:
<div v-if="selectedDateData"> {{ selectedDateData }} </div> <div v-else> No data exists for the selected date. </div>
This ensures you handle cases where the user's data or the specific date key doesn't exist without breaking your app.
内容的提问来源于stack exchange,提问作者DenisMasot

