我正在制作示例Vue应用。我实现了一个可用于创建和更新操作的表单。
<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>
当父组件执行router.push('/another-route');
子组件时,将引发错误,指出未定义发布模型。
父组件如下:
<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>
我尝试添加一些默认道具,但是它不起作用。
props: {
post: {
title: '',
'body': ''
},
errors: {
}
}
有人知道我该如何解决吗?
答案 0 :(得分:1)
通过以下操作设置default
值:
// PostForm
props: {
post: {
type: Object,
default: () => ({}),
}
errors: {
type: Object,
default: () => ({}),
}
}