在 v-for 循环中从 [ ] 获取“_id”并在数据中重用它 // vue cli
get "_id" from [ ] in v-for loop and reuse it in data // vuecli
我在 [postArray] 中循环以获得一些 posts,每个 post 都有自己的“_id”。我想重用这个“_id”来为正确的 post.
添加喜欢
这是 v-for 循环:
<div class="posts" v-for="(element, index) in postArray" :key="index">
<p>{{ element.title }}</p>
<p>{{ element.content }}</p>
<p>{{ element.likes.length }}</p>
<button @click="addLike">Add Like</button>
</div>
这是我想将我的 ID 存储在 postId:
中的数据
data() {
return {
title: "",
content: "",
postArray: [],
postId: "",
};
},
这是我想重用 _id 的方法:
async addLike() {
const url =
"https://dw-s3-nice-master-cake.osc-fr1.scalingo.io/post/like";
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "bearer " + localStorage.getItem("token"),
},
body: JSON.stringify({
postId: this.postId,
}),
};
const response = await fetch(url, options);
const data = await response.json();
console.log(data);
this.postId = data.posts._id;
console.log(this.postId);
},
还有console.log(数据)的屏幕:
console.log screenshot
[在此处输入图片描述][2]
尝试将 _id 发送到您的方法:
<button @click="addLike(element._id)">Add Like</button>
然后接收:
async addLike(id) {
...
postId: id,
...
我在 [postArray] 中循环以获得一些 posts,每个 post 都有自己的“_id”。我想重用这个“_id”来为正确的 post.
添加喜欢这是 v-for 循环:
<div class="posts" v-for="(element, index) in postArray" :key="index">
<p>{{ element.title }}</p>
<p>{{ element.content }}</p>
<p>{{ element.likes.length }}</p>
<button @click="addLike">Add Like</button>
</div>
这是我想将我的 ID 存储在 postId:
中的数据data() {
return {
title: "",
content: "",
postArray: [],
postId: "",
};
},
这是我想重用 _id 的方法:
async addLike() {
const url =
"https://dw-s3-nice-master-cake.osc-fr1.scalingo.io/post/like";
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "bearer " + localStorage.getItem("token"),
},
body: JSON.stringify({
postId: this.postId,
}),
};
const response = await fetch(url, options);
const data = await response.json();
console.log(data);
this.postId = data.posts._id;
console.log(this.postId);
},
还有console.log(数据)的屏幕:
console.log screenshot
[在此处输入图片描述][2]
尝试将 _id 发送到您的方法:
<button @click="addLike(element._id)">Add Like</button>
然后接收:
async addLike(id) {
...
postId: id,
...