使用传递的 prop 作为变量动态访问对象 属性,在 Vue 2 和 Vuex returns 上出错

Dynamically access object property using passed down prop as variable, on Vue 2 & Vuex returns error

我已经尝试了几个小时来解决这个问题,但我无法做到。我已经检查了这 2 个问题,但它们没有帮助我:

Dynamically access object property using variable

Dynamically access object property using variable

唯一可能的是 @chacham15 的回答说“小心:javascript 编译器会在这里出错,因为它们不重命名字符串,但会重命名对象属性”。

如果是这样,我该如何解决?

我的objective是动态访问this.$store.state.countries.spain.name属性,所以会访问西班牙、德国等。我什么都试过了:

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

我还尝试制作一个函数,该函数接受 name 变量并将其分配给函数内的一个 const 变量,但什么也没有。 name 变量是一个字符串,我可以 console.log 它没有问题,这就是为什么我不明白发生了什么。

当我使用 this.$store.state.countries["spain"].name 时它只 return 是 属性,所以我知道 属性 存在并且它可以 return 没有错误。我的问题是当我尝试使用变量访问 属性 时。

这是代码:

<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>

这是父 Vue 文件:

<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>

我通过从 parent.

发送所有元素作为道具解决了这个问题

这是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>

这是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>