1.在定义组件时调用内建的 $emit
方法并传入事件的名字,来向父级组件触发一个事件enlarge-text:
Vue.component('blog-post', { props: ['post'], template: ` <div class="blog-post"> <h3>{{ post.title }}</h3> <button v-on:click="$emit('enlarge-text')"> Enlarge text </button> <div v-html="post.content"></div> </div> ` })
代码解释:<button v-on:click="$emit('enlarge-text')">:监听click事件,click事件被触发时触发enlarge-text事件
2.用 v-on
在上述组件上监听这个事件,就像监听一个原生 DOM 事件一样:
<blog-post ... v-on:enlarge-text="postFontSize += 0.1" ></blog-post>
代码解释:v-on:enlarge-text:监听enlarge-text事件,enlarge-text事件被触发时执行postFontSize += 0.1