Reputation: 133
I've tried for a few hours already to fix this problem and I can't manage to do so. I've checked these 2 questions but they didn't help me:
Dynamically access object property using variable
Dynamically access object property using variable
The only thing that it could be is the answer of @chacham15 that says "careful with this: javascript compilers will error here since they dont rename strings but they do rename object properties".
If that's the case, how do I solve this?
My objective is to access the this.$store.state.countries.spain.name
property dynamically, so it would access spain, germany, and so on. I've tried everything:
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've also tried making a function that takes the name
variable and assigns it to a const variable inside the function, and nothing. The name
variable is a string, and I can console.log
it properly without issues, that's why I don't understand what's happening.
It only returns the property when I use this.$store.state.countries["spain"].name
, so I know the property exists and it can return with no error. My problem is when I try to access the property using a variable.
This is the code:
<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 this is the parent Vue file:
<template>
<div class="stats">
<table>
<StatsRow v-for="el in this.$store.state.countries" v-bind:key="el.name" :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>
Upvotes: 1
Views: 529
Reputation: 133
I solved it by sending all of the elements as props from the parent.
This is the child:
<template>
<tr class="stats-row">
<td :title="`${name}`">{{name}}</td>
<td>{{newCases}}</td>
<td>{{totalCases}}</td>
<td>{{newDeaths}}</td>
<td>{{totalDeaths}}</td>
<td>{{newRecovered}}</td>
<td>{{totalRecovered}}</td>
</tr>
</template>
This is the parent:
<template>
<div class="stats">
<table>
<StatsRow v-for="el in this.$store.state.countries" v-bind:key="el.name" :active="el.active" :name="el.name" :color="el.color" :showCases="el.showCases" :showDeaths="el.showDeaths" :newCases="el.newCases" :totalCases="el.totalCases" :newDeaths="el.newDeaths" :totalDeaths="el.totalDeaths" :newRecovered="el.newRecovered" :totalRecovered="el.totalRecovered"/>
</table>
</div>
</template>
Upvotes: 1