我们提到过,不能在子组件中直接修改父组件传来的 prop 数据。
如果想要修改父组件中的原数据要怎么办呢?
这里我们可以通过自定义事件来完成这个任务。
自定义事件
现在我们用自定义事件 “upVote” 来实现点赞功能。
- 给子组件 Article.vue 绑定自定义事件:
在 App.vue 中用 v-on:upVote=“handleLikes(article)” 给 Article.vue 绑定自定义事件:
<!-- 自定义事件 upVote,调用该事件时会执行 handleLikes 方法 -->
<Article
v-for="article in articleList"
:key="article.title"
:article="article"
v-on:upVote="handleLikes(article)"
></Article>
“upVote” 是我们给自定义事件取的事件名,就像点击事件叫 “click” 一样。比较一下:点击事件 v-on:click; 自定义事件 v-on:upVote;
2.在 Article.vue 中调用自定义事件 “upVote” :
<!-- 在 template 中直接调用自定义事件 upVote -->
<button @click="$emit('upVote')">点赞