1

我想通过 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
      }
    ],
  },
4

1 回答 1

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

应该

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

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

于 2019-02-07T16:02:58.717 回答