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.