[英]vuex push into nested array
我正在尝试将 object 添加到嵌套数组中,但不确定如何使用 store / vuex 来实现。 我使用突变更新主评论数组没有问题,但我坚持如何指定将新回复 object 推送到的主评论。 pushReply 突变将回复添加到评论的每个实例。
维克斯:
export const state = () => ({
comments: [
{
id: 1,
likes: 0,
postDate: '12/22/2021 1:25pm',
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.`,
replies: [
{
id: 1,
likes: 0,
postDate: '12/22/2021 1:25pm',
name: 'Reply One',
img: '/img/avatars/image-avatar.png',
post: `Lorem ipsum
dolor sit amet consectetur adipisicing elit. Veniam a aut quis
recusandae magnam tenetur porro autem minima aspernatur
voluptatum`,
},
],
},
],
})
export const mutations = {
pushComment(state, comment) {
state.comments.push(comment)
},
pushReply(state, comment) {
state.comments.forEach((item) => {
item.replies.push(comment)
})
},
}
零件:
methods: {
addComment() {
this.isSending = true
// postDate
const newDate = new Date()
const currentDate = newDate.toLocaleDateString('en-US')
const currentTime = newDate.toLocaleTimeString([], {
timeStyle: 'short',
})
const createdAt = `${currentDate} ${currentTime}`
setTimeout(() => {
this.$store.commit('comments/pushComment', {
id: this.$store.state.comments.comments.length + 1,
likes: 0,
postDate: createdAt,
name: 'ramsesmiron',
img: this.image,
post: this.formValues.comment,
replies: [],
})
this.$formulate.reset('formAddComment')
this.isSending = false
}, 1000)
},
},
您应该指定要在哪个评论上添加此回复 object。 通过将评论 id 传递给 pushReply 或将此 id 添加到回复 object (如parentId
)。 然后,在 pushReply function 中,找到该 id 的评论并添加该回复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.