【问题标题】:How to control array state with vuex?如何使用 vuex 控制数组状态?
【发布时间】:2019-02-07 15:39:11
【问题描述】:

我想通过 vuex 读取状态数组。
但它说

“TypeError: 无法读取未定义的属性‘0’”

我猜 [0] 发生错误。
下面是一些代码。

// the code of index.vue
<template>
  <div><p>{{ rectangles[0].x }}</p></div>
</template>
<script>
  export default {
    computed: {
            rectangles () {
                return this.$store.state.rectangles
            }
    },
  }
</script>

这就是 vuex 的 store。

export default {

  state: {
    rectangles: [
      {
        x: 150,
        y: 100,
        width: 100,
        height: 100,
        fill: "red",
        name: "rect1",
        draggable: true
      },
      {
        x: 150,
        y: 150,
        width: 100,
        height: 100,
        fill: "green",
        name: "rect2",
        draggable: true
      }
    ],
  },

【问题讨论】:

  • 你能把你的代码贴在 jsfiddle、codesandbox 等地方吗?

标签: vue.js vuex


【解决方案1】:
computed: {
            rectangles () {
                return this.$store.rectangles
            }
    },

应该是

computed: {
            rectangles () {
                return this.$store.state.rectangles
            }
    },

但最好的方法是使用 getter(链接:https://vuex.vuejs.org/guide/getters.html

【讨论】:

  • 对不起。我编辑了它,因为这是一个错误。所以问题还是一样的..
  • 你可以尝试关闭标签&lt;div&gt;这里最后&lt;div&gt;&lt;p&gt;{{ rectangles[0].x }}&lt;/p&gt;
  • 您在商店中使用模块吗?
猜你喜欢
  • 1970-01-01
  • 2018-12-03
  • 2019-04-07
  • 2021-06-07
  • 2020-04-07
  • 2020-06-23
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多