为Vue中的组件设置“默认”v-on事件

时间:2017-07-13 09:39:24

标签: javascript vue.js

我有一组'文本输入'自定义组件,它们包含一些样板标记和一个'输入'元素。

将'text-input'的值输入其父级的一种方法是$在值发生变化时发出一个事件。

我需要为每个文本输入组件捕获并处理带有v-on的$ emit:

<text-input v-on:valueUpdated="storeInputValue" name='name'></text-input>
<text-input v-on:valueUpdated="storeInputValue" name='email'></text-input>
<text-input v-on:valueUpdated="storeInputValue" name='phone'></text-input>

我觉得这在代码中引入了太多的重复,我想知道是否有一种方法可以在组件模板本身上使用v-on监听器:

<template v-on:valueUpdated="storeInputValue">
    ...
</template>

每次使用该组件时,都会有一个'默认'v-on侦听器。

1 个答案:

答案 0 :(得分:0)

您可以在自定义组件上使用v-model

<强> HTML

<div id="app>
    <text-input v-model="user.name" name="'name'"></text-input>
    <text-input v-model="user.email" name="'email'"></text-input>
    <text-input v-model="user.phone" name="'phone'"></text-input>
    <h4>{{user}}</h4>
</div> 

<强>脚本

Vue.component('text-input', {
        name: 'text-input',
        template: `
        <div>
            <label>{{name}}</label>
            <input type="text" :value="value" @input="storeInputValue($event.target.value)" />
        </div>
        `,
        props: ['value', 'name'],
        methods: {
            storeInputValue(value){
                this.$emit('input', value);
            }
        }
    });

    //parent component
    new Vue({
        el: '#app',
        data: {
            user: {
                name: '',
                email: '',
                phone: ''
            }
        }
    }); 

这是 example fiddle

相关问题