Transferring an Array of Objects to a Vue.js Component

I'm just starting out in web development and experimenting with creating a front end using vuejs and vuetify. I've encountered an issue where I can't seem to pass an array of objects to a component.

Here is the code snippet:

In my main page, I have the following lines to use the component:

<template>
   ...
   <v-content>
      ...
      <list-2 :objectsProps="clients"/>
      ...
   </v-content>
   ...
</template>

-----------------------
<script>
import List2 from "./components/List2";


export default {
  name: "App",
  components: {
    List2
  },
  data() {
    return {
      ...
      clients: [],
      ...
    };
  },
  ...
  mounted() {
    this.clients = [
      {
        title: "Client1",
        description: "Unknown"
      },
      {
        title: "Client2",
        description: "Unknown"
      },
      {
        title: "Pradier",
        description: "Unknown"
      }
    ];
  }
};
</script>

And here is how my component looks like:

<template>
    <v-card>
        <v-list two-line subheader>
            <v-subheader>List</v-subheader>

            <v-list-tile v-for="object in objects" :key="object.title" avatar>
                <v-list-tile-avatar>
                    <v-icon x-large>account_circle</v-icon>
                </v-list-tile-avatar>

                <v-list-tile-content>
                    <v-list-tile-title>{{ object.title }}</v-list-tile-title>
                    <v-list-tile-sub-title>{{ object.description }}</v-list-tile-sub-title>
                </v-list-tile-content>

                <v-list-tile-action>
                </v-list-tile-action>
            </v-list-tile>
        </v-list>
    </v-card>
</template>


<script>
export default {
  name: "List2",
  props: {
    objectsProps: []
  },
  data() {
    return {
    };
  },
  computed:{
      objects: function(){
          return this.objectsProps
      }
  }
};
</script>

At this point, I'm still learning about Vue.js and struggling to understand why this error keeps occurring. My goal is to pass a list of objects (which could represent clients, vehicles, or anything else) to my component.

The List2 component should not care about what it's displaying as long as it receives objects with a title and a description.

I opted for a computed property in the component because I wasn't sure if doing a v-for on the props was recommended.

However, I keep encountering this error:

TypeError: Cannot read property 'filter' of undefined
    at render (vuetify.js:7048)
    at createFunctionalComponent (vue.runtime.esm.js:4056)
    at createComponent (vue.runtime.esm.js:4246)
    at _createElement (vue.runtime.esm.js:4416)
    at createElement (vue.runtime.esm.js:4353)
    at vm._c (vue.runtime.esm.js:4485)
    at List2.vue?36c9:37
    at Proxy.renderList (vue.runtime.esm.js:3701)
    at Proxy.render (List2.vue?36c9:13)
    at VueComponent.Vue._render (vue.runtime.esm.js:4540)

Accompanied by these warnings:

[Vue warn]: Invalid prop: type check failed for prop "objectsProps". Expected , got Array.

found in

---> <List2> at src/components/List2.vue
       <VContent>
         <VApp>
           <App> at src/App.vue
             <Root>
vue.runtime.esm.js:587 [Vue warn]: Error in render: "TypeError: Cannot read property 'filter' of undefined"

found in

---> <List2> at src/components/List2.vue
       <VContent>
         <VApp>
           <App> at src/App.vue
             <Root>

Despite not having any filter properties in my main page or component, these errors persist.

So my questions are: Am I approaching this correctly, or am I missing something in my implementation? What steps should I take to resolve this issue?

If you have any advice or tips for a beginner like me, I would greatly appreciate them! Thank you!

Answer №1

To set a default value for your property, define it in the props section like this:

props: {
    objectsProps: {
        type: Array,
        default() {
            return [];
        }
    }
}

By the way:

I decided to use a computed property on the component because I wasn't sure if using a v-for directly on the props is recommended.

However, after further consideration, there is no need for a computed property in this case.

Answer №2

Your Code Breakdown...

Vue gives the option of defining a prop with a specific data type, such as:

props: {
  foo: String
}

or allowing for multiple valid types like this:

props: {
  foo: [String, Number] // foo can be a `String` or a `Number`
}

The type array ([String, Number] in the example above) must not be empty:

props: {
  foo: [] // invalid: missing types
}

Solution...

If your aim was to enable type checking for the prop to ensure Vue only accepts values of type Array, use the correct syntax:

props: {
  foo: Array
}

Alternatively, if you wanted to set an empty array as the default value for the prop:

props: {
  foo: {
    default: () => []
  }
}

You can even do both together:

props: {
  foo: {
    type: Array,
    default: () => []
  }
}

demo

I don't have a filter property on my main page or component, so I'm not sure why...

While I couldn't replicate that error based on the provided code snippet, it's possible that a third-party library/component used Array#filter on your array prop.

Answer №3

One of the issues I encountered was an empty section within my list:

<v-list-tile-action>
</v-list-tile-action>

This empty section was triggering a filter error, but once removed, everything worked smoothly. Thanks to all for your guidance!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Traversing a hierarchical JSON structure reminiscent of a tree object

I am working with a complex object structure, var cObj = { name: 'Object1', oNumbers: 3, leaf: [ { name: 'Inner Object 1', oNumbers: 4, leaf: [] }, { name: 'Inner Object 2', oN ...

VueJS events for right clicking up and down

I am currently utilizing Vue version 2.1.10. My approach involves using the @contextmenu event to identify right-click events. However, I aim to also detect both upwards and downwards right-click events. Is there a way for me to achieve this? ...

Unspecified OrbitControls Compatibility Issue between Angular2 and Three.js

I'm running into issues trying to set up OrbitControls in my Angular2 project. I managed to display a scene with a box, but I'm struggling to move the camera. Upon investigation, I found that my OrbitComponent, responsible for defining orbit con ...

Utilizing React Selector: Propagating the onChange Event Up Two Components

Struggling to pass an onChange event from React selector through two components back up to the parent App. The issue is that e.target.value is coming back as undefined, indicating that the event might not be returning properly. Can someone pinpoint what&ap ...

Output JSON data to an HTML5 table

Here is a code snippet to retrieve data: function fetchInformation(){ $.get('http://mywebsite.net/getFile.php', function(data) { var result = JSON.parse(data); } The returned JSON data is as follows: Object {0: "11", 1: ...

Creating a dynamic dropdown in a Rails application using the simple_form gem

In my Rails application, I have a straightforward has_many and belongs_to relationship. Using simple_form, I am looking to dynamically adjust the dropdown options based on the selection made by the user. Models class Processor < ApplicationRecord ...

Tips for utilizing the 'map' function with nested arrays within an array (JSON)

Below is the JSON data provided: users = [{ "name": "alex", "id":123, "surname":"xx", tarriff: { "id":1, "name":"free" } }, { "name": "tom", "id":124, "surname":"henry", tarriff: { "id":1, "name": ...

Ways to integrate a CSS file into XSLT

I have a CSS file that looks like this: .table_class1DeffCell { border-top-width : 1; border-left-width : 1; border-right-width : 1; border-bottom-width : 1; } .table_class11DeffCell { border-bottom-color : 000000; border-top-color : 000000; border-right- ...

What is the best way to output a variable that is returned by a function?

Here is a function I have: function findAddressViaGoogle(address){ var geocoder = new google.maps.Geocoder(); geocoder.geocode( { 'address': address }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { ...

How to refresh component after clearing dates in Vuetify datepicker

Currently, I am working with a datepicker in Vuetify JS and I need to find a way to clear the dates and refresh the component. In addition, there is a v-data table that is filtered based on the dates range array. I am exploring options to either add a &ap ...

Mapping a JavaScript object to an MVC model: A comprehensive guide

I have a JavaScript object as shown below: $scope.docPropIdentityModel = { Owner: {OwnerID:"", OwnerName: ""}, }; I need to send this object to my MVC controller using an AJAX call. Let's say the controller looks like this: controll ...

Issues with customizing material-UI styling are persisting

Recently delving into the world of material UI, I have encountered an issue while trying to customize the CSS of a material UI tabs component. <Tab key={`${tab}_${index}`} classes={{ flexcontainer: css.tabFlexContainer }} disableRip ...

Trustpilot Authentication Error: Grant_type Not Recognized

I am attempting to utilize the Trustpilot API for sending email review invitations. Before making the call, I need to obtain an access token as per Trustpilot's documentation. However, when implementing the function below, I am encountering an error i ...

Access the blob file saved in the indexedDB on an iOS device or iPad

Greetings, I am currently fetching a file using axios in the following manner: return axios({ method: "get", url: URL, responseType: "blob", }) .then((response) => { return { ...val, ...

Conceal the results of echoing json_encode

One dilemma I encountered was passing an array from PHP to JavaScript using json_encode and ajax. The only method that seemed available was to use echo json_encode($var) This approach printed out the contents of $var on the page due to the echo statement ...

DaisyUI nested collapse components featuring a dropdown menu

Here's an update following the discussion in this thread. I've implemented the solution suggested there into my Vue component, modified the collapse section, and turned it into a nested collapse with multiple collapse elements nested inside. The ...

Animate the height transition of contenteditable after a line of text is added (using shift+enter) or removed

Currently, the contenteditable attribute is being utilized on the <div> tag to enable autogrow functionality similar to a textbox. Additionally, there is an attempt to incorporate a height transition. While most aspects are functioning correctly, the ...

What is the best way to retrieve an attribute from an object dynamically using JavaScript?

Inside my object, I have the following values: obj.resposta1 obj.resposta2 obj.resposta3 obj.resposta4 How can I access each value inside a loop like this: for ( var int = 1; int < 5; int++) Thank you, Celso ...

An approach to looping through arrays within an object in JavaScript

I have a JSON structure that consists of an array containing arrays, each holding dictionary elements. This data is retrieved from a function-based view. I am looking to iterate through all the elements and filter out arrays with empty dictionaries. data. ...

Controlling the maximum number of components displayed on each row in a loop or map using React

I'm having some trouble with this seemingly simple task and could use some guidance. Any suggestions would be greatly appreciated. Thank you. My Current Situation Currently, I am working with React.js and have an array containing 20 elements. What ...