Using Vue to create a component that binds an array as its data source

Having trouble binding an array as a variable and accessing it in the child component, resulting in the variable being undefined. Is there a way to pass an array from a view to a component so that the component can use this array to create a child component for each item?

I was able to create a loop in a component and use the array to generate sub-components for each item successfully. However, I want to make this component dynamic so it can receive a variable array with items from a parent component.

Parent view:

<template>
    <div class="choose-method-container">
        <choose-method-component :availablemethods="availablemethods" v-model="availablemethods" v-bind:title="title" v.bind:items_per_row="items_per_row" />
    </div>
</template>


<script>
    import ChooseMethodComponent from 

    '../components/ChooseMethodComponent.vue';

        export default {
            components: {
                ChooseMethodComponent
            },
            methods: {

            },

            data: function() {
                return {
                    title: 'Choose user type',
                    items_per_row: 2,
                    availablemethods: [
                      {title: 'Data',  description: '', route: '/data'},
                      {title: 'Sales & Support',  description: '', route: '/sales'},      
                    ]
                }
            },
    </script>

Child component:

<template>
    <div class="choose-method-inner-container">
        <div class="card-container row flexbox" v-for="chunk in productChunks">
            <stepcard-component v-for="step_card in chunk" class="step-card"
                v-bind:key="step_card.value"
                v-bind:title="step_card.title"
                v-bind:description="step_card.description"
                v-bind:name="step_card.name"
                v-bind:value="step_card.value"
                v-bind:view="step_card.view"
                >
            </stepcard-component>
        </div>


        <div class="button-container right">
            <button type="submit" class="btn waves-effect waves-light" :disabled="choose_method_disabled"  v-on:click="choose_method">
                Choose method
            </button>
        </div>
    </div>
</template>


<script>
    import lodash from 'lodash';
    import StepCard from './StepCard.vue';

    export default {
        components: {
            StepCard
        },

        data: function() {
            return {
                choose_method_disabled: true,
            }
        }, 

        mounted() {

              console.log('mounted methods', {availablemethods: this.availablemethods, title:this.title});
            this.productChunks();
        },


            computed: {

            },

            props: {
                availablemethods: Array,
            },

            methods: {
                choose_method: function() {
                    console.log('choose_method', this.method_view);
                    if(!this.method_view)
                        return;

                        this.$router.push({name: this.method_view});
                },

                productChunks() {
                    console.log('methods', this.availablemethods);
                    if(!this.availablemethods){
                        console.log('self', {self:this});
                        return;
                    }
                    var methods = this.availablemethods.forEach(function(method, index){
                        if(!method.name)
                            method.name= '';

                        if(!method.view)
                            method.view= '';

                        if(!method.value)
                            method.value= '';

                        if(!method.description)
                            method.description= '';

                        if(!method.title)
                            method.title= '';

                        return method;
                    });            
                    let chunks = lodash.chunk(methods, this.items_per_row);
                    console.log('productChunks', {chunks:chunks});
                    return chunks;
                }
            }
        }
    </script>

Encountering issues trying to access availablemethods in the child component which logs as undefined. Any solutions to successfully pass the array without explicitly declaring and setting the array data in the child component?

Answer №1

I believe that the issue lies within your code snippet

var methods = this.availablemethods.forEach()
. It seems to be returning methods as undefined.

You can try restructuring it with something like the following (although untested):

productChunks() {
      let methods = [];
      this.availablemethods.forEach((method, index) => {
                    if(!method.name)
                        method.name= '';

                    if(!method.view)
                        method.view= '';

                    if(!method.value)
                        method.value= '';

                    if(!method.description)
                        method.description= '';

                    if(!method.title)
                        method.title= '';

                     methods.push(method);

                });

                let chunks = lodash.chunk(methods, this.items_per_row);
                return chunks;
},

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

The data from the Flickr API is consistently unchanging

I created a simple weather app that retrieves weather data using a "POST" request and displays it successfully. Users have the ability to search for weather by city, and I wanted to enhance the app by loading an image of that city through a separate jQuer ...

limitation in bootstrap ensures that only one collapse element is open at any

Hey, can someone help me fix this code? I'm trying to make it so that only one element opens at a time, but I can't seem to figure out how. Right now, if I click on two elements, they both open and the other one doesn't close. This is what ...

Using Vue to transfer data from one component to another by passing props to an element

I'm currently exploring a method to pass a Vue prop to the a tag within the second component. It needs to be a dynamic prop, so I cannot specifically import it into the component. First fragment <script> export default { name: 'first&apo ...

Display the header on every single page using puppeteer

            Whenever I enable displayHeaderFooter, the header does not display. It only works if I add margin to @page in my CSS, but this causes the page height to increase by the margin value and content to overflow beyond the page boundaries. Is ...

Searching for the element that triggered the event using jQuery or JavaScript

Can anyone offer tips on how to use console.log to identify the element that triggered a hover event? I'm trying to debug an issue specifically on iOS. I'm not looking to locate the specific item that the action was performed on, but rather what ...

Asynchronous Function Implementation of Cookies in JavaScript

Here's my query: Is it possible to store a cookie within an async function? For example, creating a cookie from this fetch and then accessing it later within the same function while the fetch continues to update the value each time the function is ex ...

Struggling with implementing ng-repeat in AngularJS for displaying HTML content

I stumbled upon a post that covers pretty much what I'm trying to achieve: AngularJS - Is it possible to use ng-repeat to render HTML values? Currently, the code appears like this and displays correctly as text: <div ng-repeat="item in items.Item ...

Looking for a JavaScript (Angular) event listener to trigger when closing pages and tabs

I am looking for an event that will only work when closing a page or tab, but should not be triggered when the page is refreshed. I am aware of the "beforeunload" event, but it also gets activated on page refresh. Below is the code snippet I am currently ...

How to Pass Values in handleChange Event in Typescript

I have noticed that most online examples of handling change events only pass in the event parameter, making the value accessible automatically. However, I encountered an error stating that the value is not found when trying to use it in my handleChange fun ...

Combining the Powers of VueJs and Laravel

Currently, I am diving into Vuejs and building a feature that allows users to mark a message as their favorite. However, I've encountered the following error. Any guidance on how to resolve this would be highly appreciated. [Vue warn]: Failed to mo ...

Guide on accessing an array within a JSON object?

I have the following JSON object: [ { "comments": [ { "created_at": "2011-02-09T14:42:42-08:00", "thumb": "xxxxxxx", "level" ...

Tooltipster fails to function with elements that are dynamically created

I've been struggling with this issue for several days now, but I can't seem to find a solution. In my JavaScript code, I have a function that generates HTML after an Ajax call is completed. I call this function in the following manner: $(documen ...

Why does the implementation of my interface differ from what is specified in the TypeScript documentation?

Currently delving into the world of TypeScript documentation https://www.typescriptlang.org/docs/handbook/2/classes.html Specifically focusing on the section implements Clauses, an interesting revelation surfaces: A Word of Caution It’s worth noting t ...

How can I get the class name of the drop destination with react-dnd?

Imagine having this component that serves as a drop target module. import { useDrop } from 'react-dnd'; import './css/DraggableGameSlot.css'; type DraggableGameSlotProps = { className: string, text: string } function Draggable ...

Combining Data in React Arrays

I have an array with different group types and I need to merge the results if the grouptype is the same. const locationss = [ { grouptype: "Name1", id: "1", servicetype: [ { name: "Morning", price: "5& ...

What is the best way to ensure that this component transfers its value to a higher-level parent component?

I started out with 2 components - a search filter and an iterator within the same component App.vue. Here's how it was structured: App.vue <v-text-field :search="search" v-model="search" label="type here to filter&q ...

Having trouble with testing axios web service promises to return results using Jest in a Vue.js application

In the process of developing a new application with Vue.js and axios, I am focusing on retrieving stock market details based on company names. To kickstart the application, I am compiling all the names of US-based S&p 500 companies into a JavaScript ar ...

How to Toggle the "active" Class Among Child Elements in vueJS 2

I'm interested in learning how to implement this functionality using vue.js. Currently, I am able to toggle the active class on a single item, but when I click on another item, the active class remains on the previous item. Here is my current setup: ...

Issue with accessing form in Angular 6 Reactive forms for custom validator functionality

I am facing an issue with creating a password validation for reactive forms in Angular. Every time I try to verify the password, I get a “Cannot read property 'get' of undefined” error in the console. I have tried different methods to access ...

Using Vuex in the router: A comprehensive guide

I am having trouble accessing data from the store in the router. I have attempted three different methods, but none of them seem to be working correctly. Here are the methods I tried: // ReferenceError: store is not defined console.log(store.state); // ...