首页 > 解决方案 > 如何在计算方法和mapState中分配数组中的动态参数

问题描述

你好,这是我的计算方法:

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

如果我把 state.festival.aftermovies [0] 它工作但如果我尝试在 url 中获取 id,id 是未定义的,请你帮帮我

标签: vue.jsvuexcomputed-propertiesmapstatetoprops

解决方案


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

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>


推荐阅读