Pavle Ilic
Pavle Ilic

Reputation: 25

Why the focus doesn't work when i click on input (Vue)?

I have a problem, when I want to focus on some input, I must click twice, and I don't know how set cursor at the end of input. I tried with $refs, but something deeper is going on. Any suggestion?

HTML CODE

<div class="input-container">
  <h3 class="field-value" v-show="!showField('name')" @click="focusField('name')">{{ user.name }}</h3>
  <input v-model="user.name" v-show="showField('name')" id="user-name" type="text" ref="test" class="field-value form-control" @focus="focusField('name')" @blur="blurField">
</div>

<div class="input-container">
 <h3 class="field-value" v-show="!showField('email')" @click="focusField('email')">{{ user.email }}</h3>
 <textarea name="testing" id="editableTextArea" cols="30" rows="10" v-model="user.email" v-show="showField('email')" type="email" class="field-value form-control" @focus="focusField('email')" @blur="blurField"></textarea>
</div>

VUE CODE

data() {
    return {
        user: {
            name: pa.data.text1,
            email: pa.data.text2
        },
        editField: '',
    }
},
methods: {
    hi(){
        this.$refs.test.$el.focus();
        console.log(1);
    },
    focusField(name) {
        this.editField = name;
    },
    blurField() {
        this.editField = '';
    },
    showField(name) {
        return (this.user[name] == '' || this.editField == name)
    },
}

Upvotes: 0

Views: 1943

Answers (1)

Abhinav Kumar
Abhinav Kumar

Reputation: 3036

You can use setTimeout to apply the focus, it's not recommended but you can use it, as you have some specific use case here.

Here is the change required

focusField(name) {
            this.editField = name;
            setTimeout(()=>{
              this.$refs[name].focus(); // access the ref and make it focus after a delay make sure element appear in the DOM
            },200);
            
        },

You also need to change some of the method bindings from input, like a blur, when you are moving to any other element blur will call automatically.

Also declare all the ref for inputs elements.

Here is the stackblitz

Upvotes: 3

Related Questions