【问题标题】:get "_id" from [ ] in v-for loop and reuse it in data // vuecli在 v-for 循环中从 [ ] 获取“_id”并在数据中重用它 // vue cli
【发布时间】:2021-12-04 00:39:25
【问题描述】:

我在 [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 screenshot

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

【问题讨论】:

    标签: javascript vue.js vue-cli


    【解决方案1】:

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

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

    然后接收它:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      • 2017-12-01
      • 2021-05-28
      • 1970-01-01
      • 2020-07-01
      • 2018-04-06
      • 1970-01-01
      相关资源
      最近更新 更多