J_shelfwood's avatar

Vue js lose focus event on input

Hey guys,

I've got this component that consists of a button and a input field with display: none, when one clicks the button it is replaced by a input field and their cursor is placed inside this input field. However, I'd like to make it revert back when you click outside of this field. Is there some kind of event that tracks a user's focus on the input?

<template>
    <div class="categoryCreate">
        <section class="categoryCreate__button" v-if="!showfield" @click="showfield = true">
            <button class="base__button">Add Category</button>
        </section>
        <input class="categoryCreate__textfield" type="text"
            v-model="category.name"
            v-else
            @keyup.enter="createCategory()"
            placeholder="Enter a name + enter"
            autofocus>
    </div>
</template>

<script>
    export default
    {
        data() {
            return {
                category: {
                    name: '',
                    category_id: ''
                },
            showfield: false
            }
        },
        props: ['parentcategory'],
        methods: {
            createCategory() {
                this.category.category_id = this.parentcategory
                this.$http.post('/api/categories', this.category).then((response) => {
                    Bus.$emit('new-category')
                    this.category.name = ''
                    this.showfield = false
                }, (response) => {
                  console.log('failed to store')
       
                });
            }
        }
    }
</script>
0 likes
4 replies
xdega's avatar

You can simply use the "blur" event in your HTML syntax. Like so: v-on:blur="some-method-here"

4 likes
J_shelfwood's avatar

Thanks for letting me know, I actually didn't know this was a feature in Vue 2.0 Still retreiving the package like a noob :p

Please or to participate in this conversation.