Vue.js 3 在方法中使用 ref 对输入使用自动对焦

Ash*_*hko 6 focus vue.js vuejs3 vue-composition-api

我使用 Vue2,但我最近尝试了 Vue 3。

我有一个简单的问题:

 <input ref="myinput" />
 <button @click="submitData" />
Run Code Online (Sandbox Code Playgroud)

我想在函数“submitData”中将“焦点”设置为“myinput”。在 Vue 2 中它很简单 (this.$refs ...),但在 Vue 3 中,它们使它变得复杂。我看到了“设置”的例子,但对我没有用+我认为你只能从元素访问“值”。

有没有办法对方法内部的元素执行“焦点”?

Bou*_*him 22

您仍然可以使用 Vue 3 做同样的事情,但是如果您使用合成 api,则会有一些区别:

选项API:

const {
  createApp
} = Vue;
const App = {

  data() {
    return {

    }
  },
  methods: {
    submitData() {
      this.$refs.myinput.focus()
    }
  },
  mounted() {

  }
}
const app = createApp(App)
app.mount('#app')
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@3.0.0-rc.11/dist/vue.global.prod.js"></script>

<div id="app">
  Vue 3 app
  <input ref="myinput" />
  <button @click="submitData">
  Submit
  </button>
</div>
Run Code Online (Sandbox Code Playgroud)

组合API:

const {
  createApp,
  ref,
  onMounted,

} = Vue;
const App = {

  setup() {
    const myinput = ref(null)

    function submitData() {
      myinput.value.focus()
    }

    return {
      myinput,
      submitData
    }
  }
}
const app = createApp(App)
app.mount('#app')
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@3.0.0-rc.11/dist/vue.global.prod.js"></script>

<div id="app">
  Vue 3 app
  <input ref="myinput" />
  <button @click="submitData">
  Submit
  </button>
</div>
Run Code Online (Sandbox Code Playgroud)


Aki*_*kif 11

我发现这里缺少最简单的答案

<input type="text" autofocus />
Run Code Online (Sandbox Code Playgroud)

  • 这仅适用于首页加载或重新加载页面时。 (7认同)

MrE*_*uar 11

在某些情况下,当输入隐藏在 v-show 或 v-if 下时,需要执行 nextTick 才能使焦点起作用。

<span
    v-show="!editMode"
    @click="handleEditionMode"
>
    {{ content }}
</span>
<input
    v-show="editMode"
    ref="input"
    v-model="content"
    aria-describedby="item-content"
    name="content"
    type="text"
    tabindex="0"
    @focusout="editMode = false"
    @keydown.enter="editMode = false"
/>
Run Code Online (Sandbox Code Playgroud)
const input = ref(null),
    editMode = ref(false);

const handleEditionMode = () => {
    editMode.value = true;
    nextTick(() => {
        input.value.focus();
    });
};
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你,谢谢你,谢谢你!我一直在为这个问题绞尽脑汁,而这正是我的困惑中所缺少的。 (4认同)

小智 5

如果有人在这个问题上寻找一种在 Vue3 中设置特定元素的自动对焦的方法,您可以使用Vue 自定义指令来实现它

const { createApp, onMounted } = Vue;

const app = createApp({})

// Register a global custom directive called `v-focus`
app.directive('focus', {
  // When the bound element is mounted into the DOM...
  mounted(el) {
    // Focus the element
    el.focus()
  }
})

app.mount('#app')
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@next"></script>

<div id="app">
    <input />
    <input v-focus />
    <input />
</div>
Run Code Online (Sandbox Code Playgroud)