Vuex 存储更新所有实例,我只想更新当前实例

Vuex store updating all instances, I only want current instance updated

我正在构建一个简单的博客页面,用户可以在其中喜欢和不喜欢评论。我当前的问题是,每当用户点击“addLike”或“subtractLike”方法时,所有喜欢的评论都会更新,而不仅仅是当前被点击的评论。

商店:

export const state = () => ({
  comments: [
    {
      id: 1,
      likes: 0,
      name: 'amyrobson',
      img: '/img/avatars/image-amyrobson.png',
      post: `Impressive! Though it seems the drag feature could be improved.
              But overall it looks incredible. You've nailed the design and the
              responsiveness at various breakpoints works really well.`,
    },
  ],
})

export const mutations = {
  pushComment(state, comment) {
    state.comments.push(comment)
  },
  addLikes(state) {
    state.comments.forEach((element) => element.likes++)
  },
  subtractLikes(state) {
    state.comments.forEach((element) => element.likes--)
  },
}

组件:

 <button @click="addLike">
        <img src="/img/icon-plus.svg" />
      </button>

      <p class="py-3 text-primaryBlue">{{ comment.likes }}</p>

      <button
        @click="subtractLike">
        <img src="/img/icon-minus.svg" />
      </button>

<script>
export default {
  data() {
    return {
      reply: false,
    }
  },
  },
  methods: {
    addLike() {
      this.$store.commit('comments/addLikes')
    },
    subtractLike() {
      this.$store.commit('comments/subtractLikes')
    },
  },
}
</script>

那是因为您要增加 所有 条评论的点赞数,而不管它们的 ID。为了增加 特定 评论的 link,您需要传递某种标识符来识别您的评论。该标识符应该是唯一的:在这种情况下,我们假设 id 字段是唯一的。

然后,在您的组件中,您需要使用以下信息(标识符)提交变更:

<button @click="addLike(comment.id)">
  <img src="/img/icon-plus.svg" />
</button>

<p class="py-3 text-primaryBlue">{{ comment.likes }}</p>

<button @click="subtractLike(comment.id)">
  <img src="/img/icon-minus.svg" />
</button>

<script>
export default {
  data() {
    return {
      reply: false,
    }
  },
  },
  methods: {
    addLike(id) {
      this.$store.commit('comments/addLikes', id)
    },
    subtractLike(id) {
      this.$store.commit('comments/subtractLikes', id)
    },
  },
}
</script>

然后您将需要更新您的提交定义以包含该标识符。使用该标识符找到您想要 increment/decrement:

like 属性 的评论
addLikes(state, id) {
  const foundComment = state.comments.find(comment => comment.id === id);
  if (foundComment) foundCommment.likes++;
},
subtractLikes(state, id) {
  const foundComment = state.comments.find(comment => comment.id === id);
  if (foundComment) foundCommment.likes--;
},

p/s:记住你数组中的对象是引用,所以foundComment只是对[=15中原始评论对象的引用=], 这允许你直接改变它。