【问题标题】:Vuex store updating all instances, I only want current instance updatedVuex 商店更新所有实例,我只想更新当前实例
【发布时间】:2022-01-12 16:53:43
【问题描述】:

我正在构建一个简单的博客页面,用户可以在其中喜欢和不喜欢 cmets。我当前的问题是,每当用户点击“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>

【问题讨论】:

  • 您在这两种方法中对存储的 cmets 数组应用了一个 forEach 函数...您需要传递您喜欢/不喜欢的评论并且只影响该记录。
  • @TremendusApps 你会在商店里应用这个逻辑吗?还是组件本身?我尝试传入 vuex,但收到“未定义”。我知道这一定是我忽略的一些简单的事情

标签: javascript vue.js nuxt.js vuex


【解决方案1】:

那是因为您正在增加 所有 cmets 的点赞数,而不管他们的 ID 是什么。为了增加特定评论的链接,您需要传递某种标识符来识别您的评论。该标识符应该是唯一的:在这种情况下,我们假设 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>

然后您将需要更新您的提交定义以包含该标识符。使用该标识符查找您想要增加/减少其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 只是对state.comments 中原始评论对象的引用,它允许您直接对其进行变异。

【讨论】:

    猜你喜欢
    • 2021-09-05
    • 2012-09-24
    • 2017-11-09
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多