Vue - 使用refs聚焦元素目标

时间:2017-11-21 09:33:51

标签: javascript dom vue.js focus refs

单击span class =“before-click”时,
我希望它隐藏起来,输入class =“after-click”代替 并且显示的输入标签必须是聚焦的!
问题是当我尝试使用$ refs.afterClick访问该DOM并给它.focus()时,意外错误显示.focus()不是函数。
如何解决这个问题? 感谢。

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>

2 个答案:

答案 0 :(得分:13)

将焦点事件包装在nextTick中 - 这将推迟焦点事件,直到DOM更新并显示输入。

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

&#13;
&#13;
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();
       });
      }
    },
  },
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

另一个技巧是设置超时(使用setTimeout),直到重新渲染完成为止(此处是一个示例):

<input type="text"  ref="input"   >

 methods: {
    setFocus: function() {
      // Note, you need to add a ref="input" attribute to your input.
      this.$refs.input.focus();
    },

 created() {
    setTimeout(x => {
      this.$nextTick(() => this.setFocus()); // just watch out with going too fast !!!
    }, 1000);