首页 > 解决方案 > 在 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) 的屏幕:

console.log 截图

[在此处输入图片描述][2]

标签: javascriptvue.jsvue-cli

解决方案


尝试将 _id 发送到您的方法:

<button @click="addLike(element._id)">Add Like</button>

然后接收它:

async addLike(id) {
  ...
  postId: id,
  ...

推荐阅读