MazPhoneNumberInput Vue.js 上的自动对焦

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

我正在以这种方式使用 MazPhoneNumberInput 组件(https://maz-ui.com/components/maz-phone-number-input):

<MazPhoneNumberInput
    v-model="phoneNumber"
    v-model:country-code="countryCode"
    show-code-on-list
    :preferred-countries="['DE', 'US', 'GB']"
    noFlags
    />

并且想在手机输入上设置自动对焦。

MazPhoneNumberInput 组件本身没有 autofocus 属性,但它基于具有 autofocus 属性的 MazInput 组件(https://maz-ui.com/components/maz-input): screenshot

我尝试通过 javascript 使用 onMounted 方法设置焦点:

import AppLayout from "@/Layouts/Auth/AppLayout.vue";
import MazPhoneNumberInput from 'maz-ui/components/MazPhoneNumberInput'
import {ref, onMounted} from 'vue'

const phoneNumber = ref()
const countryCode = ref('DE')

const focusInput = () => {
    phoneNumber.value.focus();
};

onMounted(focusInput);

但是没有成功。

如何在手机输入上设置自动对焦?

laravel vue.js inertiajs
1个回答
0
投票

这可以使用 template ref 来完成,它可以访问组件的 DOM 元素。由于根元素只是多个其他元素的包装,因此需要额外的查询来获取实际的电话输入,然后您可以将其聚焦:

onMounted(async () => {
  const phoneEl = phone.value.$el // MazPhoneNumberInput root DOM element
  const phoneInput = phoneEl.querySelector('input[type=tel]') // inner input DOM element

  await nextTick() // can focus after next DOM update
  phoneInput.focus()
})
© www.soinside.com 2019 - 2024. All rights reserved.