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

新手上路,请多包涵

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

我有一个简单的问题:

  <input ref="myinput" />
 <button @click="submitData" />

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

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

原文由 Ashko 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 918
2 个回答

你仍然可以使用 Vue 3 做同样的事情,但是如果你使用 composition api 会有一些不同:

选项API:

 const {
  createApp
} = Vue;
const App = {

  data() {
    return {

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

  }
}
const app = createApp(App)
app.mount('#app')
 <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>

组成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')
 <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>

原文由 Boussadjra Brahim 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果有人遇到这个问题寻找一种方法来设置 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')
 <script src="https://unpkg.com/vue@next"></script>

<div id="app">
    <input />
    <input v-focus />
    <input />
</div>

原文由 webcu 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题