将v-focus应用于页面上的第一个输入字段

问题描述 投票:0回答:1

我有一个Vue组件,我正在尝试使用v-focus自动聚焦第一个字段。但我的问题是,我的动态组件将包含在页面顶部。那么在这种情况下如何将自动对焦应用于动态包含的组件?

vue.js vue-component autofocus
1个回答
1
投票

很难说你是如​​何将输入添加到DOM,没有任何伪代码,但这是一种方法来做到这一点..

[Qazxswpoi]

CodePen mirror
new Vue({
  el: "#app",
  data: {
    inputs: ["firstName", "lastName"]
  },
  watch: {
    inputs() {
      this.$nextTick(() => {
        this.focusFirstInput();
      });
    }
  },
  methods: {
    focusFirstInput() {
      let first = this.inputs[0];
      let firstInput = this.$refs[first][0];
      firstInput.focus();
    },
    handleClick() {
      this.inputs.push("newInput");
    }
  },
  mounted() {
    this.focusFirstInput();
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.