When the view changes, the child component in Vue reports that the props are unexpectedly not defined

Currently, I am working on a sample Vue application. As part of this project, I have implemented a form that serves the dual purpose of facilitating both create and update operations.

<template>
    <div>
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label>Post Title:</label>
                    <input type="text" class="form-control" v-model="post.title">
                    <div v-if="errors['post.title']" class="invalid-feedback">
                        {{errors['post.title'].join(' ')}}
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label>Post Body:</label>
                    <textarea class="form-control" v-model="post.body" rows="5"></textarea>
                    <div v-if="errors['post.body']" class="invalid-feedback">
                        {{errors['post.body'].join(' ')}}
                    </div>
                </div>
            </div>
        </div>
        <br />
        <div class="form-group">
            <button class="btn btn-primary">Create</button>
        </div>
    </div>
</template>

<script>
    export default {
        props: ['post', 'errors']
    }
</script>

Upon redirecting to another route using router.push('/another-route');, the child component encounters an error stating that the post model is undefined.

The parent component code snippet is as follows:

<template>
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card card-default">
                <div class="card-header">
                    Create Post
                </div>
                <div class="card-body">
                    <form @submit.prevent="handlePostCreate">
                        <PostForm v-bind:post="post" v-bind:errors="errors"/>
                    </form>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import Post from './../../models/Post';
    import PostForm from './../../components/forms/PostForm';
    import PostService from './../../services/PostService';
    export default {
        data() {
            return {
                post: new Post(),
                postService: new PostService(),
                errors: {}
            }
        },
        methods: {
            handlePostCreate() {
                this.postService.store(this.post)
                    .then(res => {
                        router.push('/posts');
                    })
                    .catch(err => {
                        this.errors = err.errors;
                    });
            }
        },
        components: {
            PostForm
        }
    }
</script>

I attempted to define default props, but unfortunately, the proposed solution did not resolve the issue.

props: {
    post: {
        title: '',
        'body': ''
    }, 
    errors: {

    }
}

If anyone has any suggestions or ideas on how to rectify this problem, your input would be greatly appreciated.

Answer №1

To establish default values, use the instructions below:

// PostForm
props: {
  post: {
    type: Object,
    default: () => ({}),
  }
  errors: {
    type: Object,
    default: () => ({}),
  }
}

Check out the Reference

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

I must update the menu to show only one sub-menu at a time, ensuring that multiple menus cannot be displayed simultaneously

When I click on a menu option, it displays correctly, but when I click on another option, both are displayed. The goal is to only display one at a time. https://i.sstatic.net/J6vLf.png $('.sub-menu ul').hide(); $(".sub-menu a").click( ...

A function injected into a constructor of a class causes an undefined error

As I delve into learning about utilizing typescript for constructing API's, I have encountered a couple of challenges at the moment. Initially, I have developed a fairly straightforward PostController Class that has the ability to accept a use-case wh ...

The value of a select box cannot be retrieved until it has been clicked on

I am working with a selectBox element in my code: <select class="span2" name="filterYear" id="filterYear" style="margin-right:10px;"> <% for (var i = 0; i < years.length; i++) { %> <% if (years[i] == selectedYear) { %> ...

Could anyone provide a breakdown of the code listed below?

Help me unravel the mysteries of Promises! I have a challenge ahead of me. I need to write a function that will display 3000 after 3 seconds, then display 2000 after 2 seconds, and finally 1000 after 1 second. This is what I have so far: 'use strict& ...

Unable to retrieve data within a customer component

Currently, I am engrossed in a personal project where I am crafting an odds comparison platform using Next.js for the frontend and Django REST Framework in conjunction with Django Channels for the backend. Despite immersing myself in the Next.js documentat ...

The jqGrid colModel is failing to execute a function as expected

Within the given code snippet, the function attrSetting is invoked. However, when I modify it to {"name":"A", "index":"0", "cellattr":attrSetting}, the code executes smoothly. But here lies the issue - cellattr interprets it as a string rather than a fun ...

Utilizing Vue 2 and Axios to toggle visibility of a div based on the response of an Axios request

I have a div on my website <div class="ui-alert" v-show="isCaptchaError"> ... </div> The variable isCaptchaError is initialized in my Vue instance: const form = new Vue({ el: '#main-form', data: { ...

obtaining attribute values from chosen items in a multiselect dropdown menu

I am using jQuery to create a multi-select element. For instance, consider the following example: <select multiple id="multiple"> <option value="1" type="Alice">Option 1</option> <option value="2" type="Bob">Option 2</o ...

Using jQuery to crop an SVG view box

I'm currently working on a sticker website project for a client who requires the ability to crop an image within a specific SVG shape, resembling a Halloween face (shown below). The uploaded image should be displayed only within this shape while hidi ...

Experiencing difficulties with node and asynchronous programming

I'm attempting to use async-waterfall in order to fetch data from an API, save it as JSON, and then store it in a database. Here is a snippet of the code I have so far. Can someone assist me with this process? async.waterfall([ function getBo ...

A WordPress website featuring the impressive capabilities of the Three.js JavaScript 3D library

I attempted to integrate the Three.js JavaScript 3D library into my WordPress website by including three.min.js in various parts: Within the body of a post <script src="/three.min.js"></script> In the footer <script type='text/ ...

Conceal elements within a div using the 'elementFromPoint' function

In my HTML, I have a div that contains an icon and some text. I want to make it so that when I hover over the div with my mouse, only the div itself is visible to the 'elementFromPoint' function. How can I achieve this? Here is an example of th ...

Is it possible to provide an offset to the raycaster in three.js?

I am currently working on developing a pool game using three.js. As part of the gameplay, I have incorporated a helper ruler that indicates the direction of the hit. This ruler is represented by an ArrowHelper and is positioned at y=0, which aligns with ...

Using a three.js texture with a JSON object

Currently, I am working on a customization project where I am using three.js to export an HTML5 canvas as a 3D preview. My goal is to have the texture placed only on the front side, but it seems to appear on all sides instead. This is the code I am using: ...

Troubleshooting: Issues with Three.js Node TextureLoader

Currently, I am working on rendering objects server-side using node with three.js. I have successfully implemented the OBJLoader and MTLLoader, and I am utilizing MockBrowser to simulate the DOM. Strangely, when I take a screenshot of the model, I can se ...

Express: fetch not capable of setting cookie

I am implementing a cookie setting feature with Express, using the code snippet below: app.use(require('cookie-parser')()); app.get('/a', function (req, res) { console.log(req.cookies); res.cookie('aaa', 'bbb&apo ...

Creating custom services that modify or extend default services in a shared module

I am facing a dilemma with my shared module in AngularJS 1.6.5. This module is designed to be used across multiple applications, each requiring different services within the module to be overridden to cater to their specific needs. These variations are mai ...

Is Cognito redirect causing issues with Angular router responsiveness?

When employing social login via AWS Cognito, Cognito sends a redirect to the browser directing it to the signin redirect URL after signing in. In this case, the specified URL is http://localhost:4200/home/. Upon receiving this redirect, the application in ...

Validate user credentials with React Router Dom

In the process of developing a React application, I encountered an issue with the Header component. This specific component includes a Menu button that should toggle the sidebar and trigger a logout function, but only when the user is logged in. My approa ...

Managing JSON data sent using PHP

After exploring numerous syntaxes from various sources on the internet, I am hesitant to reveal my struggles as it may be hard to distinguish fact from fiction. So... This snippet shows a part of my HTML code: var jsonData = { address: 'address& ...