javascript - 无法让 Vue 专注于输入

标签 javascript vue.js

我正在尝试使用 this.$refs.cInput.focus()(cInput 是一个 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() {
        ...
    }
  }
});

最佳答案

您可以使用 nextTick() 回调:

When you set vm.someData = 'new value', the component will not re-render immediately. It will update in the next “tick”, when the queue is flushed. [...]

In order to wait until Vue.js has finished updating the DOM after a data change, you can use Vue.nextTick(callback) immediately after the data is changed. The callback will be called after the DOM has been updated.

(source)

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

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

关于javascript - 无法让 Vue 专注于输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56093602/

相关文章:

vue.js - vue js 的响应式图像网格库

javascript - 用于在 Photoshop 中的位图图像中创建文本的 Photoshop 脚本

javascript - asp.net 无法加载 css3 派

events - Vue.js - 什么是 self 修饰符

javascript - 如何在 vuetify 的浅色主题中启用自定义颜色的深色模式?

vue.js - Vuex 模块 - 无法正确设置 ..mapGetters

javascript - Laravel Vue.js - 包含 vue-router 的最简单方法?

javascript - 如何在 javascript 中获得 1.450 = 1.5? (四舍五入到小数点后一位)

javascript - 返回 Sequelize 中行的自定义值?

.net - 带有 AJAX(更新面板)的 TinyMCE 永远没有值(value)