Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
81
rated 0 times [  87] [ 6]  / answers: 1 / hits: 24714  / 7 Years ago, tue, november 21, 2017, 12:00:00

When span class=before-click is clicked,

I want it hidden, and input class=after-click show up instead.

And the showed up input tag must be on focused!

The problem is when I try to use $refs.afterClick to access that DOM and give it .focus(), an unexpected error shows that .focus() is not a function.

How to solve this issue?
Thanks.





var myApp = new Vue({
el: '#app',
data: {
onEdit: false,
msg: 'Something in here',
},
methods: {
switchAndFocus() {
if(!this.onEdit) {
this.onEdit = true;
this.$refs.afterClick.focus();
}
},
},
});

<script src=https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js></script>
<div id=app>
<span class=before-click @click=switchAndFocus() v-show=!onEdit>{{msg}}</span>
<input type=text class=after-click ref=afterClick :value=msg v-show=onEdit>
</div>




More From » dom

 Answers
31

Wrap the focus event in a nextTick - this will defer the focus event until the DOM has updated and displayed the input.


https://v2.vuejs.org/v2/api/#Vue-nextTick




var myApp = new Vue({
el: '#app',
data: {
onEdit: false,
msg: 'Something in here',
},
methods: {
switchAndFocus() {
if(!this.onEdit) {
this.onEdit = true;
this.$nextTick(function(){
this.$refs.afterClick.focus();
});
}
},
},
});

<script src=https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js></script>
<div id=app>
<span class=before-click @click=switchAndFocus() v-show=!onEdit>{{msg}}</span>
<input type=text class=after-click ref=afterClick :value=msg v-show=onEdit>
</div>




[#55876] Friday, November 17, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tiffany

Total Points: 46
Total Questions: 97
Total Answers: 84

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
;