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

Ott*_*tto 5 vue.js vue-component vuejs2

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

Vue warn]: Error in render: "TypeError: Cannot read property 'length' of undefined"
Run Code Online (Sandbox Code Playgroud)

数据: 'spaces' 是从 store 中获取的。

    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'
            ])
    }
Run Code Online (Sandbox Code Playgroud)

模板:

<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>
Run Code Online (Sandbox Code Playgroud)

店铺:

    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'
                    }
                ]
            }
        ]} });
Run Code Online (Sandbox Code Playgroud)

vue chrome add on 说这个信息在组件中:

在此处输入图片说明

Moh*_*sen 9

始终在检查长度之前,确保您的财产已设置,然后检查长度

<v-flex v-if="spaces && spaces.length < filterMaxLength">
Run Code Online (Sandbox Code Playgroud)

更新 ECMAScript 2020

您也可以为此目的使用可选链接

<v-flex v-if="spaces?.length < filterMaxLength">
Run Code Online (Sandbox Code Playgroud)


Max*_*Max 6

您应该使用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>
Run Code Online (Sandbox Code Playgroud)