繁体   English   中英

无法让 Vue 专注于输入

[英]Cant get Vue to focus on input

我正在尝试使用this.$refs.cInput.focus()cInput是一个参考),但它不起作用。 我可以按g并且输入应该会弹出并且光标应该集中在其中,准备输入一些数据。 它正在显示,但焦点部分不起作用。 我在控制台中没有错误。

Vue.component('coordform', {
  template: `<form id="popup-box" @submit.prevent="process" v-show="visible"><input type="text" ref="cInput" v-model="coords" placeholder =""></input></form>`,
  data() {
    {
      return { coords: '', visible: false }
    }
  },
  created() {
    window.addEventListener('keydown', this.toggle)
  },
  mounted() {
  },
  updated() {
  },
  destroyed() {
    window.removeEventListener('keydown', this.toggle)
  },
  methods: {
    toggle(e) {
      if (e.key == 'g') {
        this.visible = !this.visible;
        this.$refs.cInput.focus() //<--------not working
      }
    },
    process() {
        ...
    }
  }
});

您可以使用nextTick()回调:

当您设置vm.someData = 'new value'时,组件不会立即重新渲染。 当队列被刷新时,它将在下一个“滴答”中更新。 [...]

为了在数据更改后等到 Vue.js 完成更新 DOM,您可以在数据更改后立即使用Vue.nextTick(callback) DOM 更新后将调用回调。

来源

在您的切换功能中使用它,例如:

methods: {
  toggle(e) {
    if (e.key == 'g') {
      this.visible = !this.visible;
      this.$nextTick(() => this.$refs.cInput.focus())
    }
  }
}

不确定这是否仅适用于 Vue3,但如果您想从组件内部显示对输入框的关注,最好设置一个转换。 在过渡中,有一个名为@after-enter 的事件。 所以在enter上的动画过渡完成后,@after-enter就被执行了。 @after-enter 将是在您的组件出现后始终执行的事件。

我希望这可以帮助所有遇到以下问题的人:

  ***this.$nextTick(() => this.$refs.searchinput.focus());***

它可能无法按您希望的方式工作,因为最初的焦点可能仍然在父元素上并且输入元素尚未显示,或者如果您将其放置在已安装的状态下,它只会执行一次,无论您如何显示/hide 组件(通过 v-if 或 v-show), nextTick 行已经在 mount() 上执行,并且不会在组件再次显示时触发。

请尝试以下解决方案:

<template>
   <transition name="bounce" @after-enter="afterEnter" >
     <div>
         <input type="text" ref="searchinput" />
     </div>
   </transition>
</template>

<script>
methods: {
       afterEnter() {
            setTimeout(() => {
                
                this.$refs.searchinput.focus();
                
            }, 200);
        },
}
</script>

就我而言,nextTick 效果不佳。

我刚刚使用了 setTimeout,如下例所示:

doSearch () {
  this.$nextTick(() => {
    if (this.$refs['search-input']) {
      setTimeout(() => {
        this.$refs['search-input'].blur()
      }, 300)
    }
  })
},

我认为您的案例代码应如下所示:

toggle(e) {
  if (e.key == 'g') {
    this.visible = !this.visible;
    setTimeout(() => { this.$refs.cInput.focus() }, 300)
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM