【发布时间】:2021-04-15 13:48:11
【问题描述】:
我想做什么:
我单击 cmets.vue 中的按钮,该按钮假定添加在文本区域中键入的注释。这个动作将被发送到 event.vue 来监听这个动作。当它听到这个动作时,它将激活一个将评论推送到列表中的方法。然后我想显示这个 cmets 列表。我不知道为什么它不起作用。
评论.vue:
<template>
<div>
<form>
<label>Comments</label>
<textarea v-model="comment"/>
<input class="button" @click.prevent="addComment" type="submit" value="Add comment">
</form>
</div>
</template>
<script>
export default {
data () {
return {
name: 'Arnulf',
comment: ''
/* timeAndDate: Date */
}
},
methods: {
addComment () {
const comment = {
name: this.name,
comment: this.comment
/* timeAndDate: this.timeAndDate */
}
console.log('hello')
this.$emit('submitted', comment)// THIS WONT EMIT FOR SOME REASON
this.comment = ''
}
}
}
</script>
Event.vue:
<template>
<div>
<CommentList :comments="listOfComments"></CommentList>
<Comments @submitted="addComment"></Comments>
</div>
</template>
<script>
import CommentList from '@/components/CommentList'
import Comments from '@/components/Comments'
export default {
data () {
return {
listOfComments: []
}
},
name: 'Event',
components: {
CommentList,
Comments
},
methods: {
addComment (comment) {
console.log('bruh')
this.listOfComments.push(comment)
}
}
}
</script>
commentlist.vue:
<template>
<div>
<h3>Kommentarer:</h3>
<ul>
<li v-for="(comment, index) in comments" :key="index">
{{comment.name}}:
<br/>
"{{comment.comment}}"
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'CommentList',
props: {
comments: {
type: Array
}
}
}
</script>
编辑:添加了其余代码,因此可以跟踪所有逻辑。
【问题讨论】:
-
listOfComments是被动的吗? Aka 你在data中定义了吗? -
是的,它是在数据中定义的。 console.log('bruh') 永远不会命中。
-
@Kenso33,我已经在 SO 代码 sn-ps(发布为下面的答案)以及 Vue SFC Playground 中尝试了您的代码。它在任何地方都运行良好。如果能提供某种问题重现的代码sn-ps就更好了。
-
您使用的是
vue2或vue3?
标签: javascript vue.js