【问题标题】:Setting a 'default' v-on event for a component within Vue为 Vue 中的组件设置“默认”v-on 事件
【发布时间】:2017-12-18 00:21:41
【问题描述】:

我有一组“文本输入”自定义组件,其中包含一些样板标记和一个“输入”元素。

将 'text-input' 的值传入其父级的一种方法是在值发生更改时 $emit 一个事件。

我需要为每个文本输入组件使用 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 侦听器。

【问题讨论】:

  • storeInputValue 到底是做什么的?每个组件的实现是否相同,还是您需要知道哪个特定组件发出了它?为什么不让&lt;text-input&gt;v-model 一起工作?
  • 我需要知道发出它的组件以及值。 storeInputValue 会将值存储到父数据对象中。

标签: javascript vue.js


【解决方案1】:

您可以在自定义组件上使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    • 2013-09-28
    • 2019-05-18
    • 1970-01-01
    • 2019-11-12
    相关资源
    最近更新 更多