@keyup.enter unexpected result

时间:2018-07-24 10:13:22

标签: javascript vuejs2 vue-component

I have a single form with two vue 2.0 components. On both components I have a single input field, combined with a @keyup.enter:

(Component#1) @keyup.enter="addItem"

(Component#2) @keyup.enter="addVariantItem"

If the focus is on one of the inputs and I press enter, BOTH functions addItem and addVariantItem are called.

<template>
    <input type="text" class="form-control form-control-sm" id="variant-sku" placeholder="SKU" v-model="variantItemSku" @keyup.enter="addVariantItem()">
</template>

<script>
    export default {
        data: function (){
            return {
                variantItemSku: ''
            };
        },
        methods: {
            addVariantItem: function () {
                axios
                    .post('/articles/' + this.article + '/variants', {
                        sku: this.variantItemSku
                    })
            }
        }
    }
</script>

<style scoped>

</style>

<template>
    <input type="text" class="form-control form-control-sm" id="cross-seller-sku" placeholder="SKU" v-model="crossSellerSku" @keyup.enter="addItem()">
</template>

<script>
    export default {
        data: function (){
            return {
                crossSellerSku: ''
            };
        },
        methods: {
            addItem: function () {
                axios
                    .post('/articles/' + this.article + '/cross-sellers', {
                        sku: this.crossSellerSku
                    })
            }
        }
    }
</script>

<style scoped>

</style>

i.e. I am in the "variant-sku" input and hit enter, addVariantItem() gets called, but also addItem in the other component ... Other way around, focus on "cross-seller-sku" causes the same result.

Is there some way to limit the @keyup.enter to the current focussed input? Right now it only works if one of the two inputs is focussed, if there is no focus nothing happens.

Is there a bug, so that the keyup.enter is called on every input?

1 个答案:

答案 0 :(得分:0)

解决方案是将@ keyup.enter =“ function”更改为@ keydown.enter.prevent =“ function” 因为输入的默认行为是在@keydown上起作用,而不是在@keyup上起作用,所以您必须覆盖它。