最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Vue - using refs to focus an element target - Stack Overflow

programmeradmin0浏览0评论

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=".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>

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>

Share Improve this question asked Nov 21, 2017 at 9:33 Arel LinArel Lin 9182 gold badges13 silver badges25 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 35

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>

发布评论

评论列表(0)

  1. 暂无评论