【发布时间】: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