javascript - 在 v-for 循环中从 [ ] 获取 "_id" 并在数据中重用它 // vuecli
问题描述
我在 [postArray] 中循环获取一些帖子,每个帖子都有自己的“_id”。我想重用这个“_id”来为正确的帖子添加喜欢。
这是 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(data) 的屏幕:
[在此处输入图片描述][2]
解决方案
尝试将 _id 发送到您的方法:
<button @click="addLike(element._id)">Add Like</button>
然后接收它:
async addLike(id) {
...
postId: id,
...
推荐阅读
- python - 楼层划分如何不根据记录的规则给出结果?
- node.js - 如果外键约束处于活动状态,则使用 sequelize 迁移更改表的过程
- json - 使用 bash 脚本查询 json 文件
- symfony4 - Command 类中没有 SUCCESS 常量
- powerbi - 在 Power BI 中,如何删除名称以“NewHire”开头的行并计算剩余员工数?
- javascript - 如何使用 js 音频 api 播放多个音频
- javascript - 如何删除 div 中的所有内容,而不删除 div 本身,只使用 JavaScipt 而不是 jQuery?
- opencl - OpenCL 在加载 RGB 纹理缓冲区时返回“OUT_OF_RESOURCES”错误,并且在 RGBA 下一切正常
- python - 在 python 中创建套接字池(多处理)
- javascript - 同步 XMLHttpRequest Strophe.js