【问题标题】:how to assign a dynamic parameter in an array in the computed method and mapState如何在计算方法和mapState中分配数组中的动态参数
【发布时间】:2021-02-12 14:07:36
【问题描述】:

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

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

如果我输入 state.festival.aftermovies [0] 它可以工作,但如果我尝试在 url 中获取 id,id 是未定义的,你能帮我吗

【问题讨论】:

  • 这应该可以state.festival.aftermovies[this.$route.params.id]

标签: vue.js vuex computed-properties mapstatetoprops


【解决方案1】:

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

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

【讨论】:

  • 不,它不起作用,它返回给我答案:Cannot read property 'id' of undefined
【解决方案2】:

非常感谢是的,确实我们无法在 ma​​pState 中访问 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>

【讨论】:

    猜你喜欢
    • 2013-11-29
    • 1970-01-01
    • 2020-07-01
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 2021-12-15
    相关资源
    最近更新 更多