如何在计算方法和mapState中的数组中分配动态参数

问题描述

您好,这是我的计算方法

computed:
    mapState({
    aftermovie: (state) => state.festival.aftermovies[id]
  }),id: {
      set() { return this.$route.params.id}
    },

如果我将state.festival.aftermovies [0]放上了,但是如果我尝试在网址中获取ID,则ID未定义,请您帮忙

解决方法

我认为问题是您无法访问this中的mapState或其他计算的属性,请尝试以下操作:

computed: {
  ...mapState({
    aftermovies: (state) => state.festival.aftermovies
  }),id() {
    return this.$route.params.id
  },aftermovie() {
    return this.aftermovies[this.id]
  }
}
,

非常感谢,确实我们无法在 mapState 中访问 this ,这是功能性解决方案:

data() {
    return {
    // -1 because the aftermovie index is 1 and the index in the array starts at 0
      id: this.$route.params.id - 1
    }
  },computed:
    mapState({
      aftermovies: (state) => state.festival.aftermovies
    }),

最后访问数据

<template>
  <div>
    <div class="container text-center">
      <div>
        {{ aftermovies[this.id].id }}
        {{ aftermovies[this.id].name }}
        {{ aftermovies[this.id].video }}
      </div>
    </div>
  </div>
</template>