无法让 Vue 专注于输入

Gab*_*lla 2 javascript vue.js

我正在尝试使用this.$refs.cInput.focus()( cInputis a ref) 但它不起作用。我将能够点击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() {
        ...
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

Sov*_*ina 6

您可以使用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())
    }
  }
}
Run Code Online (Sandbox Code Playgroud)