Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting props for components using v-for in Vue JS

I have a PhoneCard.vue component that I'm trying to pass props to.

<template>
    <div class='phone-number-card'>
        <div class='number-card-header'>
            <h4 class="number-card-header-text">{{ cardData.phone_number }}</h4>
            <span class="number-card-subheader">
                {{ cardData.username }}
            </span>
        </div>
    </div>
</template>

<script>
export default {
    props: ['userData'],
    components: {
    },
    data() {
        return {
            cardData: {}
        }
    },
    methods: {
        setCardData() {
            this.cardData = this.userData;
            console.log(this.cardData);
        }
    },
    watch: {
        userData() {
            this.setCardData();
        }
    }
}

The component receives a property of userData, which is then being set to the cardData property of the component.

I have another Vue.js component that I'm using as a page. On this page I'm making an AJAX call to an api to get a list of numbers and users.

import PhoneCard from './../../global/PhoneCard.vue';
export default {
    components: {
        'phone-card': PhoneCard
    },
    data() {
        return {
            phoneNumbers: [],
        }
    },
    methods: {
        fetchActiveNumbers() {
            console.log('fetch active num');
            axios.get('/api').then(res => {
                this.phoneNumbers = res.data;

            }).catch(err => {
                console.log(err.response.data);
            })
        }
    },
    mounted() {
        this.fetchActiveNumbers();
    }
}

Then once I've set the response data from the ajax call equal to the phoneNumbers property.

After this comes the issue, I try to iterate through each number in the phoneNumber array and bind the value for the current number being iterated through to the Card's component, like so:

<phone-card v-for="number in phoneNumbers" :user-data="number"></phone-card>

However this leads to errors in dev tools such as property username is undefined, error rendering component, cannot read property split of undefined.

I've tried other ways to do this but they all seem to cause the same error. any ideas on how to properly bind props of a component to the current iteration object of a vue-for loop?

like image 939
Daniel Park Avatar asked Oct 31 '25 17:10

Daniel Park


1 Answers

Try

export default {
    props: ['userData'],
    data() {
        return {
            cardData: this.userData
        }
    }
}
like image 129
Bert Avatar answered Nov 03 '25 07:11

Bert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!