我正在尝试内联编辑文章并提交表单中的值。但是,v-model
值在提交时为空。
在下面查看我的代码。因此,顶部表格仅适用于新文章。在我的v-for
中,在“查看”和“编辑”模式之间进行了切换。
<template>
<div>
<h2>Articles</h2>
<hr />
<form class="mb-3" @submit.prevent="addArticle">
<div class="form-group">
<input class="form-control" placeholder="Title" v-model="article.title" />
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Bodytext" v-model="article.body"></textarea>
</div>
<button type="submit" class="btn btn-light btn-block">Add new</button>
</form>
<hr />
<div class="card card-body mb-2" v-for="article in articles" v-bind:key="article.id">
<template class="article-row" v-if="edit === article.id">
<form @submit.prevent="editArticle">
<div class="form-group">
<input class="form-control" placeholder="Title" v-model="article.title" />
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Bodytext" v-model="article.body"></textarea>
</div>
<!-- <input type="hidden" v-model="article.id" /> -->
<button type="submit" class="btn btn-light btn-block">Update</button>
</form>
</template>
<template v-else>
<h3>{{ article.title }}</h3>
<p v-html="article.body"></p>
<hr />
<div>
<button @click="toggleEditMode(article.id)" class="btn btn-warning">Edit</button>
<button @click="deleteArticle(article.id)" class="btn btn-danger">Delete</button>
</div>
</template>
</div>
</div>
</template>
<script>
export default {
data() {
return {
articles: [],
article: {
id: "",
title: "",
body: ""
},
article_id: "",
edit: false
};
},
created() {
this.fetchArticles();
},
methods: {
fetchArticles(page_url) {
let vm = this;
page_url = page_url || "/api/articles";
fetch(page_url)
.then(res => res.json())
.then(res => {
this.articles = res.data;
vm.makePagination(res.meta, res.links);
})
.catch(err => console.log(err));
},
addArticle() {
console.log(JSON.stringify(this.article));
fetch("/api/article", {
method: "post",
body: JSON.stringify(this.article),
headers: {
"content-type": "application/json"
}
})
.then(res => res.json())
.then(data => {
this.article.title = "";
this.article.body = "";
alert("Article added!", "success");
this.fetchArticles();
})
.catch(err => console.log(err));
},
editArticle() {
console.log(JSON.stringify(this.article));
fetch("/api/article", {
method: "put",
body: JSON.stringify(this.article),
headers: {
"content-type": "application/json"
}
})
.then(res => res.json())
.then(data => {
alert("Article updated!", "success");
this.fetchArticles();
})
.catch(err => console.log(err));
},
toggleEditMode(article_id) {
this.edit = article_id;
}
}
};
</script>
console.log(JSON.stringify(this.article));
函数第一行的editArticle
返回一个空对象(默认值)...我在做什么错了?
答案 0 :(得分:0)
您需要设置article
,然后再尝试像这样进行更新:
toggleEditMode(article_id) {
for (let index = 0; index < this.articles.length; index++) {
const article = this.articles[index];
if(article.id === article_id){
this.article = article;
break;
}
}
this.edit = article_id;
}