我正在尝试使用我想要编辑的帖子自动填充表单。问题是更新和创建表单都使用 v-model="post.title" 和 v-model="post.body" .
所以我的问题是:
PostList.vue(数据返回脚本部分)
data() {
return {
posts: [],
pagination: {},
post: {
id: '',
title: '',
body: ''
},
update: false,
post_id: '',
};
},
PostList.vue(更新脚本部分)
updatePost(post) {
this.update = true;
this.post.id = post.id;
this.post.post_id = post.id;
this.post.title = post.title;
this.post.body = post.body;
},
updatePost2() {
if (this.update === true) {
fetch('api/post', {
method: 'put',
body: JSON.stringify(this.post),
headers: {
'content-type': 'application/json',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
.then(res => res.text())
.then(data => {
this.getPosts();
})
.catch(err => console.log(err));
}
}
PostList.vue(仅 2 个表单的 Html 部分。)
<div id="newPost" class="modal fade" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<form enctype="multipart/form-data" method="post" action="" @submit.prevent="addPost">
<input type="hidden" name="_token" value=""/>
<div class="modal-header">
<h4 class="modal-title">Create Post</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" placeholder="Title" v-model="post.title" required>
</div>
<div class="form-group">
<label>Description</label>
<textarea class="form-control" placeholder="Body" v-model="post.body" required></textarea>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
<button type="submit" id="btnSave" class="btn btn-success"><i class="glyphicon glyphicon-ok"></i> Submit</button>
</div>
</form>
</div>
</div>
</div>
<div id="updatePost" class="modal fade" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<form enctype="multipart/form-data" method="post" action="" @submit.prevent="updatePost2">
<input type="hidden" name="_token" value=""/>
<div class="modal-header">
<h4 class="modal-title">Update Post</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" placeholder="Title" v-model="post.title" required>
</div>
<div class="form-group">
<label>Description</label>
<textarea class="form-control" placeholder="Body" v-model="post.body" required></textarea>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
<button type="submit" id="btnSave" class="btn btn-success"><i class="glyphicon glyphicon-ok"></i> Submit</button>
</div>
</form>
</div>
</div>
</div>