Vue.js: The property or method you are trying to access is not defined. A rendering error has occurred: "TypeError: Cannot read property ' ' of undefined"

I'm currently developing a chat app using vue.js and laravel.

My goal is to display the contacts list in a similar format to messaging apps, but I'm encountering difficulty viewing the list of users.

Within components/ContactList.vue, I'm experiencing the following errors:

Property or method "contact" is being referenced during render but is not defined on the instance.

Error in render: "TypeError: Cannot read property 'profile_image' of undefined"

TypeError: Cannot read property 'profile_image' of undefined

https://i.sstatic.net/4VfrU.png https://i.sstatic.net/J3cgT.png Here is the ContactsList.vue code snippet:

<template>
    <div class="contacts-list">
        <ul>
            <li v-for="(contact ,index) in contacts" :key="contact.id" @click="selectContact(index, contact)" 
             :class="{ 'selected': index == selected }"></li>componvue.jsCont
                <div class="avatar">
                    <img :src="contact.profile_image" :alt="contact.name">
                </div>
                <div class="contact">
                    <p class="name">{{ contact.name }}</p>
                    <p class="email">{{ contact.email }}</p>
                </div>
        </ul>
    </div>
</template>

<script>
export default {
    props: {
        contacts: {
            type: Array,
            default: [],
            
        }
    },
    data() {
        return {
            selected: 0
        };
    },
    methods: {//selectContactをおしたら
        selectContact(index, contact) {
            this.selected = index;
            this.$emit('selected', contact);
        }
    }
    
}
</script>

Also, here's the UserFactory.php code snippet:

<?php

/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\User;
use App\Message;
use Illuminate\Support\Str;
use Faker\Generator as Faker;

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/

$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'phone' => $faker->phoneNumber,
        'email' => $faker->unique()->safeEmail,
        'profile_image' => 'http://via.placeholder.com/150',
        'email_verified_at' => now(),
        'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        'remember_token' => Str::random(10),
    ];
});

$factory->define(Message::class, function (Faker $faker) {
    do {
        $from = rand(1,15);
        $to = rand(1, 15);
    } while($from == $to);
    return [
        'from' => $from,
        'to' => $to,
        'text' => $faker->sentence
    ];
});

I've gone through the documentation provided but still can't seem to resolve the issue. Here's the link to the Vue.js guide that I referenced: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

Your assistance in resolving this problem would be greatly appreciated.

Answer №1

Your ending</li> seems to be misplaced. As a result, the contact variables are appearing outside of the v-for loop.

I believe you intended it to be like this:

<ul>
    <li v-for="(contact ,index) in contacts" :key="contact.id" @click="selectContact(index, contact)" 
        :class="{ 'selected': index == selected }">
        <div class="avatar">
            <img :src="contact.profile_image" :alt="contact.name">
        </div>
        <div class="contact">
            <p class="name">{{ contact.name }}</p>
            <p class="email">{{ contact.email }}</p>
        </div>
    </li> <!-- THIS IS THE RIGHT PLACE FOR THE CLOSING TAG -->
</ul>

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

During the deployment of a ReactJS app, webpack encounters difficulty resolving folders

While developing my ReactJS app, everything ran smoothly on localhost. However, I encountered some serious issues when I tried to deploy the app to a hosting service. In my project, I have a ./reducers folder which houses all of my reducers. Here is the s ...

What could be preventing the background image from displaying properly?

I had the idea to create a game where players have to flip cards to reveal what's on the back, but I'm struggling to get the background image to display properly. As a newcomer to Vue, I'm not sure if I made a mistake somewhere. My intuition ...

Is there a way to utilize Javascript/JQuery to access and interpret PHP-generated HTML form data in a multi-dimensional array format?

I am having difficulty in reading and manipulating data from an HTML form using Javascript/JQuery. Situation: I have a sales screen displaying multiple products, and I aim to iterate through them all, analyze their contents, and showcase some of the data ...

The curious conduct of wild safari creatures

I have been using JavaScript to split my ePub chapter into pages by wrapping the code with new divs that represent separate pages. I have also created CSS styles for these new divs. Everything works perfectly when the file has a filename extension of &apos ...

How come my image is not appearing on Vue.js when fetched from the API?

While working on my laravel vue project, I encountered an issue where the image is not being fetched from the backend API. All other data is being displayed correctly except for the image. JSON: [ { "id": 1, "name": ...

Generating an HTML table using a JavaScript object dynamically

I am in the process of dynamically generating an HTML table using information from a MySQL database table. The data within the table is regularly changing, requiring the HTML table to be updated accordingly when alterations are made to the database table. ...

Disabling the 'fixed navigation bar' feature for mobile devices

Here's a code snippet that I'm working with. It has the ability to make the navigation stick to the top of the page when scrolled to. HTML <script> $(document).ready(function() { var nav = $("#nav"); var position = nav.position(); ...

Steps for adding custom text/symbols from a button on the textAngular toolbar

My goal is to include a button on the toolbar that allows users to insert © into the textangular editor (). However, I am struggling to grasp how to add functionality to my registered button. The examples provided by textangular for custom functionali ...

When additional elements follow, the button ceases to function properly in JavaScript

I am working on creating a text-based idle game that involves multiple buttons and text around them. However, I have encountered an issue where the functionality stops working when I try to add text after the "Work" button. The callback function is no lon ...

What solutions are available for resolving the devServer issue in webpack?

Any help or advice would be greatly appreciated. I have configured webpack and everything works in production mode, but the webpack-dev-server is not recognizing static files and is giving the error "Cannot get /". How can I resolve this issue? Thank you i ...

When incorporating Typescript into HTML, the text does not appear in bold as expected

Issue with bold functionality in Typescript Hey there, I am currently involved in an Angular project and I came across a problem with a function in a Typescript file that is supposed to bold a specific segment of text formatText() { ......... ...

Tips for maintaining the select dropdown open while opening the mat-menu in Angular

I am working with a mat-select component that has custom options including an additional menu item "Set as default": <mat-form-field appearance="fill"> <mat-label>Favorite food</mat-label> <mat-select> <mat-opti ...

Resource temporarily unavailable in Laravel, unable to unset currently

While working with Laravel, I encountered an issue when trying to delete a file using unset via ajax. The error message thrown by Laravel was: unlink(...) Resource temporarily unavailable After further investigation, I found that if I waited for about ...

Enhance Image Size with a Custom React Hook

I've created a function to resize user-uploaded images stored in state before sending them to the backend. const [file, setFile] = useState(null) function dataURLtoFile(dataurl, filename) { let arr = dataurl.split(','), mime = arr[0].ma ...

Tips for maintaining the state of a page submitted via Turbolinks using Rails 5 and jQuery

My current challenge involves toggling the visibility of a section when a specific element is clicked. Initially, I was able to achieve this functionality successfully. However, complications arose as my application revolves around a todo list where tasks ...

Even after modifications to the formGroup control, the value remains null when using ng-select, unless the searchTerm is provided programmatically

I need to programmatically set the value of the searchTerm using a virtual keypad, and the dropdown should display options based on the searchTerm. The form control is set to updateOn:'blur'. However, I am facing an issue where the form control ...

Adding a duplicated form causes the page to refresh unexpectedly

When the user clicks on the "#addOne" button, a clone of the previous form is displayed using jQuery. The data from these forms is relayed using Ajax to avoid refreshing the page when submitting. However, there seems to be an issue with dynamically created ...

Styling Discord with NodeJS

After coding with Python for Discord, I decided to switch to JavaScript for its wider functionality. However, I encountered a formatting issue with a specific line of code while testing out a music bot in JS. The bot was sending an embed message, but I wan ...

Having trouble converting a JSON array into a JavaScript array upon creation

I have encountered this question multiple times before and despite trying various solutions, I have not been able to find success. Summary: My goal is to retrieve the array from the classes.json file and then assign the data in the variable classes from d ...

What is a more efficient method for creating a JSON object?

Here is the code I am using: this.selectedMonths = JSON.parse(JSON.stringify(this.selectedMonths)); Once this code runs, `this.selectedMonths` will be properly formatted as a JSON object. I'm wondering if there is a more efficient way to achieve th ...