无法读取未定义的属性“长度”

时间:2018-07-03 12:38:09

标签: vue.js vuejs2 vue-component

我收到以下错误。奇怪的是,我很肯定数据在那里,因为在我的vue插件中,我可以看到它成功地从vuex存储中获取了信息。我最初的猜测是,在创建模板时,还不知为何还没有从商店中获取数据?

Vue warn]: Error in render: "TypeError: Cannot read property 'length' of undefined"

数据:“空间”是从商店中获取的。

    export default {
        name: "myspaces",
        data() {
            return {
                filterMaxLength: 3,
                selectedSpace: 0,
                selectedRoom: 0
            }
        },
        created() {
            // Default selected space (first in json)
            this.selectedSpace = this.spaces[0].id;

            // Default selected room (first in json)
            this.selectedRoom = this.spaces[0].rooms[0].id;
        },
        computed: {
            // Get 'spaces' from store.
            ...mapState([
                'spaces'
            ])
    }

模板:

<template>
      <div>  
         <v-flex v-if="spaces.length < filterMaxLength">
              <v-btn v-for="space in spaces">
                 <h4> {{space.name}} </h4>
              </v-btn>
         </v-flex>
     </div>
<template>

商店:

    import Vuex from 'vuex'

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        spaces:[
            {
                id:1,
                name:'House in Amsterdam',
                rooms:[
                    {
                        id:1,
                        name:'Bedroom Otto',
                    },
                    {
                        id:2,
                        name:'Bedroom Mischa'
                    }
                ]
            },
            {
                id:2,
                name:'Office in Amsterdam',
                rooms:[
                    {
                        id:1,
                        name:'Office 1',
                    },
                    {
                        id:2,
                        name:'Office 2'
                    }
                ]
            }
        ]} });

附加的vue chrome表示此信息位于组件中:

enter image description here

3 个答案:

答案 0 :(得分:1)

您应该使用Object.keys(spaces).length,例如:

<template>
      <div>  
         <v-flex v-if="typeof spaces !== 'undefined' && typeof spaces === 'object' && Object.keys(spaces).length < filterMaxLength">
              <v-btn v-for="space in spaces">
                 <h4> {{space.name}} </h4>
              </v-btn>
         </v-flex>
     </div>
<template>

答案 1 :(得分:0)

始终在检查长度之前,请确保先设置属性,然后再检查长度

<v-flex v-if="spaces && spaces.length < filterMaxLength">

答案 2 :(得分:0)

只是为了确保你的 vue 中有以下内容

import { mapState } from "vuex";

否则,您也可以使用 getter,例如。 :

在你的 vue 文件中

v-if="this.getSpaces.length !== 0"

在 vue 文件的计算函数中

getSpaces() {

  return this.$store.getters.getSpaces;

}

在您的商店

getters: {
    getSpaces: state => {
      return state.spaces;
    }
},
相关问题