when converting an application that uses jQuery to a Vue.js SPA (without jQuery). Currently, some jQuery statements toggle the display of hidden div’s when the associated input field has focus, this is then hidden again on blur.
In a vue.js component there is added a data option of phoneNumberHasFocus which is set to true on field focus and false on blur. This works and the display of the div toggles on focus/blur.
However, any value typed into the input field is lost on blur.
export default {
name: ‘profile’,
data: function() {
return {
phoneNumberHasFocus: false
}
},
}
<div class=”col-md-6 col-sm-8”>
<div class=”input-area”>
<input type=”text” class=”form-control” placeholder=”Phone number” name=”phoneNumber” ref=”phoneNumber” :value=”user.userdetails.phoneNumber” @focus=”phoneNumberHasFocus=true” @blur=”phoneNumberHasFocus=false” />
</div>
<div v-show=”phoneNumberHasFocus” class=”help-text”>
Please provide a phone number here if youd like us to contact you by phone when you make an enquiry. Include the area code and extension if required.
</div>
</div>
Has anyone come across this issue before or have an alternative approach to toggling display of the div when the focus is on the input field?
Solution :
Add user.userdetails.phoneNumber to the data method
export default {
name: ‘profile’,
data: function() {
return {
phoneNumberHasFocus: false
user: {
userdetails: {
phoneNumber: ‘’
}
}
}
},
}
and use v-model for 2 way binding
<input type=”text” class=”form-control” v-model=”user.userdetails.phoneNumber” placeholder=”Phone number” name=”phoneNumber” ref=”phoneNumber” v-mo=”user.userdetails.phoneNumber” @focus=”phoneNumberHasFocus=true” @blur=”phoneNumberHasFocus=false” />
Solution 2:
I was able to resolve this problem by using the v-model directive and vuex-map-fields package to provide 2-way data binding to the store, which had the desired outcome of not clearing the field value on blur whilst hiding the related div with the help text.
<div class=”col-md-6 col-sm-8”>
<div class=”input-area”>
<input
type=”text” class=”form-control” placeholder=”Phone number”
name=”phoneNumber” ref=”phoneNumber” v-model=”phoneNumber”
@focus=”phoneNumberHasFocus=true” @blur=”phoneNumberHasFocus=false” />
</div>
<div v-show=”phoneNumberHasFocus” class=”help-text”>
Please provide a phone number here if youd like us to contact you by phone when you make an enquiry. Include the area code and extension if required.
</div>
</div>
<script>
import { mapFields } from ‘vuex-map-fields’;
export default {
name: ‘profile’,
data: function () {
return {
phoneNumberHasFocus: false,
}
},
computed: {
…mapFields([
‘user.userdetails.phoneNumber’,
]),
},
mounted: function () {
this.$store.dispatch(‘fetch_user’);
},
}
</script>