I have been struggling for hours to find a solution to this problem, but so far I've had no luck. I've looked at these two questions, but they didn't provide the answers I needed:
Dynamically access object property using variable
Dynamically access object property using variable
The key point that caught my attention was @chacham15's response mentioning "careful with this: javascript compilers will error here since they don't rename strings but they do rename object properties."
If that's the issue, how can I resolve it?
My goal is to dynamically access the
this.$store.state.countries.spain.name
property, allowing me to access properties such as spain, germany, and others. I have tried various methods:
this.$store.state.countries[""+name].name
this.$store.state.countries[this.name].name
this.$store.state.countries[name].name
this.$store.state.countries[`${this.name}`].name
this.$store.state.countries[`${name}`].name
I even attempted creating a function that takes the name
variable and assigns it to a constant variable within the function, but still no success. The name
variable is a string and I can log it correctly without any issues, which makes it confusing as to what might be causing the problem.
It only returns the property when I use
this.$store.state.countries["spain"].name
, confirming that the property exists and can be accessed without errors. My struggle arises when trying to access the property using a variable.
This is the code snippet in question:
<template>
<tr class="stats-row">
<td :title="`${name}`">{{name}}</td>
<td>{{this.$store.state.countries[this.name]}}</td>
</tr>
</template>
<script lang="ts">
import Vue from 'vue';
export default Vue.extend({
name: 'StatsRow',
components: {
},
props: {
name: String,
},
});
</script>
And here is the parent Vue file:
<template>
<div class="stats">
<table>
<StatsRow v-for="el in this.$store.state.countries" v-bind:key="el.neutral" :name="el.name"/>
</table>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import StatsRow from '@/components/StatsRow.vue';
export default Vue.extend({
name: 'Stats',
components: {
StatsRow,
},
});
</script>