首页 > 其他分享 >How To Focus An Input In Vue?

How To Focus An Input In Vue?

时间:2022-12-12 16:15:24浏览次数:68  
标签:Vue refs component Focus focus How input element

1-How to Set Focus on an Input in Vue?

Sometimes it’s important to set focus on input (programmatically or by default), it is often for accessibility, and/or to make the app more convenient to use purposes.

the usual is setting it to be autofocused at Page load:

<input type="text" placeholder="I'm auto-focused" autofocus>

The only problem is that when you add the autofocus attribute to an input it will be focused once is loaded, but when you init a Vue app the focus is lost so you need to programmatically focus an element.

To use focus() programmatically you use either Vuejs or vanilla javascript:

→ in Javascript:

#html 
    <form>
      <input id="email" />
    </form>

Now grap you element using getElementById()

const input = document.getElementById('email');

Now all you have to do is to call the focus() function:

input.focus( *options* ); // Object parameter

→ in Vue.js:
Vue offers a better and easy way:

#vue template
   <template>
     <input ref="email" />
   </template>

note: Vue uses ref="something" attribute to register a reference to any HTML element or child component.

Then you use $refs, which are a much more reliable way of grabbing your elements.

const input = this.$refs.email;

Now you are allowed to use that within your method:

    methods: {
        focusInput() {
          ...
          this.$refs.email.focus();
        }
      }

Note: if you are using a Custom component you likely get this error: “focus is not a function”.
to fix this you need to make sure you are getting the root element of your custom component $el :
import CustomInput from ‘./CustomInput.vue’;

export default {
  components: {
    CustomInput,
  },
  methods: {
    focusInput() {
      this.$refs.email.$el.focus();
    }
  }
}

You may still run into some issues though…because sometimes you will have to wait for Vue to finish re-rendering.

For instance, if you change the inputs’ status from being hidden to being displayed.
You’ll need to wait for the input to be rendered before you can grab it and focus on it.

To do this you can use a method to check if the element you want to focus Is visible or not.
Here is an example:

<template>
  <div>
    <CustomInput v-if="inputIsVisible" ref="email" />
  </div>
</template>
<template>
  <div>
    <CustomInput v-if="inputIsVisible" ref="email" />
  </div>
</template>
import CustomInput from './CustomInput.vue';

export default {
  components: {
    CustomInput,
  },
  data() {
    return {
      inputIsVisible: false,
    };
  },
  mounted() {
    this.focusInput();
  },
  methods: {
    showInput() {
      // Show the input component
      this.inputIsVisible = true;

      // Focus the component, but we have to wait
      // so that it will be showing first.
      this.nextTick(() => {
        this.focusInput();
      });
    },
    focusInput() {
      this.$refs.email.$el.focus();
    }
  }
}

You can see that we have called our focusInput() method withing nextTick().
nextTick allows us to wait until the input is rendered in the DOM. Once it’s there, you will be able to grab it and focus on it.
you can read more about nextTick here https://vuejs.org/v2/api/#Vue-nextTick 38.

→ other ways to do it:

Sometimes when the input is not the root element of that el-input component (probably wrapped in a

), you will have to get it from the children of the root element.
this.$refs.input.$el.children[0].focus();

another trick is to set a time out (using setTimeout), until the re-render finishes here is an example:

<input type="text"  ref="input"   >

 methods: {
    setFocus: function() {
      // Note, you need to add a ref="input" attribute to your input.
      this.$refs.input.focus();
    },

 created() {
    setTimeout(x => {
      this.$nextTick(() => this.setFocus()); // just watch out with going too fast !!!
    }, 1000);

using the same way above you can pass props to your component,

<input-text ref="name" v-model="item.name"></input-text>
watch: {
      dialog (val) 
         if (val) {
            setTimeout(() => {
               this.$refs.name.focus();
            }, 10);
         }
      }
 }

 

参考:https://stopbyte.com/t/how-to-focus-an-input-in-vue/987

标签:Vue,refs,component,Focus,focus,How,input,element
From: https://www.cnblogs.com/sfnz/p/16976313.html

相关文章

  • Vue3.0文档学习心得--响应式工具
    1.isRef:检查某个值是否为ref。返回值是true或者falseletfoo:unknown//返回值是一个类型判定 (typepredicate),这意味着 isRef 可以被用作类型守卫。if(isRe......
  • vue实现瀑布流
    <template><divid="app"><ul><liref='waterfallItem'v-for="(item,index)inwaterfallArr":key="index">......
  • 「Vue系列」之Vue2实现当前组件重新加载
     遇到问题的场景:需要把当前组件完全还原成初始化状态,不要页面全部刷新例如:重置按钮,只刷新当前加载组件其他办法:使用vue-router重新定向到当前页面,页面不刷新使用window-r......
  • vue3 封装t点击左右箭头实现内容滑动组件
    1、组件<template><divclass="switch-tab"><divclass="switch-tab-left"@click="leftClick"><el-icon:size="24"color="rgba(99,149,255,1)"><A......
  • 项目启动报错: Vue 报错error:0308010C:digital envelope routines::unsupported
      Vue报错error:0308010C:digitalenveloperoutines::unsupported查了好多,找出原因:因为我刚装了最新的node版本18.12.1出现这个错误是因为 node.jsV17版本中最......
  • 随笔(六)『Vue项目 引入 阿里巴巴图标』
    1、进入阿里巴巴图标官网:https://www.iconfont.cn/2、随意选个图标库3、把需要的图标添加入库(购物车)4、进入购物车,下载代码5、在项目中创建文件夹:src/icon,把下载好......
  • vue视频会议录屏并保存mp4格式到本地
    项目中,在视频会议中需要添加一个录屏功能主要是利用newMediaRecorder()来实现屏幕录制功能。//录制屏幕asyncscreenRecording(){//提示用户去选择和......
  • Vue3.0文档学习心得--响应式核心
    1.ref():接受一个内部值,返回一个响应式的、可更改的ref对象.此对象只有一个指向其内部值的属性 .value。使用实例:constcount=ref(0) console.log(count.value)//......
  • Vue响应式系统原理并实现一个双向绑定
    这一章就着重讲两个点:响应式系统如何收集依赖响应式系统如何更新视图我们知道通过Object.defineProperty做了数据劫持,当数据改变的时候,get方法收集依赖,进而set方法调用......
  • Vue实战必会的几个技巧
    键盘事件在js中我们通常通过绑定一个事件,去获取按键的编码,再通过event中的keyCode属性去获得编码如果我们需要实现固定的键才能触发事件时就需要不断的判断,其实很......