Vue:如何在按钮点击时调用.focus()

ITW*_*tch 7 javascript setfocus vue.js vuejs2

vue.js昨天才开始编码,我不知道如何在没有使用"传统"JS方式的情况下"专注"文本框,就是这样document.getElementById('myTextBox').focus().

最初,我的文本框是隐藏的.我有一个"开始"按钮,当用户点击它时,会显示文本框,我想设置focus那里,可以这么说.我已经尝试过使用ref,但无济于事(见下面的代码).

HTML:

<input id="typeBox" ref="typeBox" placeholder="Type here..." />
Run Code Online (Sandbox Code Playgroud)

使用Javascript

export default {
  name: 'game',

  methods: {
    startTimer () {
      setTimeout(function () { /* .focus() won't work without this */

        /* ugly and not recommended */
        // document.getElementById('typeBox').focus()

        /* Throws the error: Cannot read property 'typeBox' of undefined */
        this.$refs.typeBox.focus()

        // ... any other options?
          // ...

      }, 1)
    }
  } /* END methods */

} /* END export default */
Run Code Online (Sandbox Code Playgroud)

有谁知道如何做到这一点?请帮忙.

更新:

添加autofocusinput不聚焦在页面加载之后的伎俩.但是在我的应用程序中,需要多次"重新聚焦"输入字段而不重新加载页面,这就是我需要一种方法来调用的原因.focus().

ITW*_*tch 13

在这里分享解决方案,万一有人遇到同样的问题......

我终于在一位资深程序员的帮助下解决了这个问题.我还能够setTimeout使用它的vue版本一路消除nextTick().

正确的JS代码:

startTimer () {
    this.$nextTick(() => {

        // this won't work because `this.$refs.typeBox` returns an array
        // this.$refs.typeBox.focus()

        //this one works perfectly
        this.$refs.typeBox[0].focus()

    })
} /* END startTimer */
Run Code Online (Sandbox Code Playgroud)

说明:

当我使用时console.log(this.$refs.typeBox),它返回了这个数组:

在此输入图像描述

这就是为什么代码工作,它必须typeBox[0].focus()代替typeBox.focus().

  • 你的数组可能是由 v-for 引起的吗?“当在 v-for 的元素/组件上使用时,注册的引用将是一个包含 DOM 节点或组件实例的数组。” (2认同)

Sri*_*mam 5

的值thissetTimeout功能将被设置为window,因为它是回调函数的一段时间之后执行的对象和它已经失去的范围this被动态地从函数被调用,其中设置关键字。

箭头函数不绑定它自己的 值this

startTimer () {
  setTimeout(() => {
    this.$refs.typeBox.focus()
  }, 1)
}
Run Code Online (Sandbox Code Playgroud)

或者

startTimer () {
  const self = this;
  setTimeout(function () {
    self.$refs.typeBox.focus()
  }, 1)
}
Run Code Online (Sandbox Code Playgroud)