在其父组件中,我们可以通过添加一个 postFontSize 数据属性来支持这个功能:

    它可以在模板中用来控制所有博文的字号:

    1. <div id="blog-posts-events-demo">
    2. <div :style="{ fontSize: postFontSize + 'em' }">
    3. <blog-post
    4. v-for="post in posts"
    5. v-bind:key="post.id"
    6. v-bind:post="post"
    7. ></blog-post>
    8. </div>
    9. </div>

    现在我们在每篇博文正文之前添加一个按钮来放大字号:

    1. Vue.component('blog-post', {
    2. props: ['post'],
    3. template: `
    4. <div class="blog-post">
    5. <h3>{{ post.title }}</h3>
    6. <button>
    7. Enlarge text
    8. </button>
    9. <div v-html="post.content"></div>
    10. </div>
    11. })

    问题是这个按钮不会做任何事:

    1. <button>
    2. Enlarge text
    3. </button>

    当点击这个按钮时,我们需要告诉父级组件放大所有博文的文本。幸好 Vue 实例提供了一个自定义事件的系统来解决这个问题。父级组件可以像处理 native DOM 事件一样通过 监听子组件实例的任意事件:

    1. <blog-post
    2. ...
    3. v-on:enlarge-text="postFontSize += 0.1"
    4. ></blog-post>

    有了这个 v-on:enlarge-text="postFontSize += 0.1" 监听器,父级组件就会接收该事件并更新 postFontSize 的值。

    有的时候用一个事件来抛出一个特定的值是非常有用的。例如我们可能想让 <blog-post> 组件决定它的文本要放大多少。这时可以使用 $emit 的第二个参数来提供这个值:

    1. <button v-on:click="$emit('enlarge-text', 0.1)">
    2. Enlarge text
    3. </button>

    然后当在父级组件监听这个事件的时候,我们可以通过 $event 访问到被抛出的这个值:

    1. <blog-post
    2. ...
    3. v-on:enlarge-text="postFontSize += $event"
    4. ></blog-post>

    或者,如果这个事件处理函数是一个方法:

    1. <blog-post
    2. ...
    3. v-on:enlarge-text="onEnlargeText"
    4. ></blog-post>
    1. methods: {
    2. onEnlargeText: function (enlargeAmount) {
    3. }

    在组件上使用 v-model

    自定义事件也可以用于创建支持 v-model 的自定义输入组件。记住:

    等价于:

    1. <input
    2. v-bind:value="searchText"
    3. v-on:input="searchText = $event.target.value"
    4. >

    当用在组件上时,v-model 则会这样:

    1. <custom-input
    2. v-bind:value="searchText"
    3. v-on:input="searchText = $event"
    4. ></custom-input>

    为了让它正常工作,这个组件内的 <input> 必须:

    • 将其 value 特性绑定到一个名叫 value 的 prop 上
    • 在其 input 事件被触发时,将新的值通过自定义的 input 事件抛出 写成代码之后是这样的:
    1. Vue.component('custom-input', {
    2. props: ['value'],
    3. template: `
    4. <input
    5. v-bind:value="value"
    6. v-on:input="$emit('input', $event.target.value)"
    7. >
    8. `
    9. })

    现在 v-model 就应该可以在这个组件上完美地工作起来了: