Is it possible to access prop properties within the ready() function?

I am seeing the error message undefined in the console, specifically originating from the ready() function.

The issue I am encountering is related to attempting to assign the value of this.users.name to this.userForm.name.

Can someone please point out what mistake I might be making?

profile-user Component

   <template>
      <input type="text" v-model="userForm.name">
   </template>

<script>
    export default {

        props: ['users'],

        ready() {
            this.userForm.name = this.users.name;
            console.log(this.users.name);
        },

        data: function () {
            return {
                userForm: {
                    name: '',
                    email: '',
                    errors: [],
                },
            }
        },
} 
</script>

HTML:

<profile-user :users="users"></profile-user>

Edit:

Parent Vue

const app = new Vue({
    el: 'body',
    data: {
        users: {}
    },

    ready: function() {
        this.fetchUser();
    },

    methods: {
        fetchUser: function() {
            this.$http.get('/api/user').then(response => this.users = response.json());
        }
    },
});

Answer №1

ready has been deprecated in Vue 2.0. It is recommended to use mounted instead of ready()

If your users is an object, consider naming it more appropriately as user_info. However, if you are passing a single user info into users with a name parameter on it, then your code should technically work.

Make sure to install and debug using vue-devtools in the dev console: https://github.com/vuejs/vue-devtools

EDIT: revised based on updated question

It seems that there may be an issue in the Parent component. The $http call takes some time to complete, causing this.users in the parent component to be undefined initially. This can lead to errors in the child component (profile-user) when trying to access userForm.name before receiving the server response.

To solve this problem, adjust the template of the profile-user component as follows:

<template>
    <div v-if="userForm">
        <input type="text" v-model="userForm.name">
    </div>
    <div v-else>
        Loading user data... Please wait
    </div>
</template>

In your development environment, the server response may be quick. However, keep in mind that the this.$http call is asynchronous, so the AJAX call will only be made after the profile-user component is fully created.

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

Utilizing AngularJS to implement checkbox selection within a table

I'm working on a method that will receive an Id from a table when a checkbox is checked and update the $scope.selected array in my Angular controller. If the checkbox is unchecked, it should remove the corresponding item from $scope.selected. Here&ap ...

Highcharts: Including plotlines in the legend

I need to include a plotline in the legend. Check out my example here. $('#container').highcharts({ xAxis: { tickInterval: 24 * 3600 * 1000, // one day type: 'datetime' }, yAxis: { plotLines: ...

Canvas - Occasionally, using lineTo() can result in crisp edges in the drawing

I've created a simple Canvas drawing app. However, I've noticed that occasionally the lineTo() command generates a line with fewer coordinates, resulting in many edges: I'm currently using the latest version of Firefox - could this issue be ...

Unable to display search results with AJAX in Select2

I'm struggling with getting the desired outcomes to display in Select2 when using AJAX. Below is my code: $(document).ready(function() { $("#producto").select2({ placeholder: 'Select a product', formatResult: productForm ...

Creating a Vue.js application using Visual Studio Code

Recently delving into the world of vue.js, I've turned to Visual Studio Code for my coding needs. Following the instructions provided in the Volar extension guide, I can see that the sample project includes a 'hello world' page (HelloWorld.v ...

Executing a JavaScript Function in the Background using Cordova

Despite the numerous questions and plugins available on this topic, finding a solution has proven to be elusive for me. The most highly recommended plugin for this issue can be found here. My goal is to run MyService in the background, subscribe to the ON ...

Enhance and Modify feature using Javascript

I'm facing two issues with my product information form. Firstly, after I submit the data, I want the input fields to be cleared automatically. Secondly, the edit function doesn't seem to work at all. I'm quite stuck on how to resolve these p ...

What is the method for assigning classes to a Vue.js Functional Component from its parent component?

Imagine a scenario where I have a functional component: <template functional> <div>Some functional component</div> </template> Now, when I render this component within a parent element with classes: <parent> <som ...

Cloned bootstrap nav tabs are controlled just like the original version

I have a unique scenario where I need to generate a series of "cards" with tabs on top (each card having tabs). To accomplish this, my plan was to use a template element that I can clone and then populate. Everything seems to work fine, except for the tabs ...

Triggering multiple functions by clicking on the Icon

I'm trying to execute two different functions when the user clicks on the Icon, but I keep getting an error that says: Expected onClick listener to be a function, instead got a value of object type. Can someone please help me figure out what I am doin ...

Removing a specific item from an array

state = { filters: ['all'] } this.state.filters.includes('humans') ? this.state.filters.filter(val => val !== 'humans') : this.state.filters.push(dropdown) I have a condition set up so that when I click on a button, ...

Determine the fill color attribute value of a rectangle using Testcafe paired with typescript

Here is a code snippet I need help with: <colored-item label="Label A" symbol-size-left="9.5" symbol-size-right="12" symbol-right="" symbol-left="<svg viewport="0 0 24 24" xmlns="http://www. ...

Hovering over a Raphael animation - What's preventing it from functioning?

I'm currently working on a pie chart using Raphael, and I want to add a tooltip that displays text when hovering over a specific segment of the chart. The hover event is functioning correctly, but I'm having trouble adjusting the tooltip text coo ...

Is it possible to conditionally redirect using Vue router?

I am in the process of creating a straightforward Vue application where the router links will be determined by the data retrieved from the server. The format of the data looks something like this: id: 1 path: "category_image/About.jpg" slug: &quo ...

Having trouble signing out in Nextjs?

As a newcomer to Reactjs and Nextjs, I am currently working on developing an admin panel. To handle the login functionality, I have implemented the following code in my index.js/login page using session storage: const data = { name: email, password: pa ...

Tips to stop automatic scrolling when tapping on a tab

Currently, I am encountering an issue with the tabs in my project. Whenever I click on a tab, the page scrolls down and I can't seem to figure out why. Below is the snippet of my HTML code: <ul class="list"> <li class="tab1 active"> ...

Learn how to show the current page number using React Js with the help of material-ui's

Take a look at the code snippet below from my App.js Component: const App = () => { const [workstations, setWorkstations] = useState([]); let [page, setPage] = useState(1); const PER_PAGE = 1; useEffect(() => { loadWorkstations(); }, [] ...

Solving compatibility problems with jquery AJAX requests on multiple browsers

searchCompanyExecutives: function(criteria, callback) { var params = $j.extend({ type: "GET", data: criteria, url: "/wa/rs/company_executives?random=" + Math.floor(Math.random() * (new Date()).getTime() + 1), ...

Utilizing Highcharts with NodeJS

Is anyone familiar with implementing Highcharts in Node.js? I am currently encountering a problem using [email protected]: var Highcharts = require('highcharts'), chart = Highcharts.chart(null, { series: [{ data: [1, 3, 2, 4 ...

Is there a way to create a new prettyphoto window by clicking on a link within the original prettyphoto window?

I have an HTML table that is dynamically constructed on the server side using AJAX. The table is displayed using prettyphoto, everything works fine up to this point. However, the last column of the table contains a link that should open an image using pret ...