Quickly Solve autofocus Failure Problem of element

  • 2021-08-12 01:50:12
  • OfStack

Reason:

autofocus is the native property of input in vue, and element also supports this method.

However, there are other components outside the el-input components in element, which cause autofocus to fail and can only be aggregated by manually calling focus methods.

Methods:

Bind ref

< el-input ref="myNameId" v-model="form.name" / >

this.$refs.myNameId.focus();

Dynamic binding ref


<el-input :ref=" 'input'+ form.id " v-model="form.name" />

this.$nextTick(()=>{
 let id = 'input'+this.form.id;
 this.$refs[id].focus();
})

Additional knowledge: element input input box automatically gets focus

When making a form in a recent project, you need to automatically scroll to the comment box and make the comment box automatically focus, which requires manually triggering the focus state of the input box.

However, element does not support the autofocus attribute, so the focus effect can only be obtained through the native js effect

document.getElementById("input").focus();

Or the focus effect can be achieved by using the ref attribute of vue:

The principle is actually very simple, Element has provided focus method, but the document does not specify how to call, the following is in el-input tag to add ref attribute, and then call the method directly where needed

< el-input v-model= "input" placeholder= "Please enter content" ref= "input" > < /el-input >


this.$nextTick(() => {
  this.$refs.input.focus()
 })

Note: One page can only have one focus effect

last and vue also support custom instructions

When the page loads, the element gets focus (note: autofocus does not work on the mobile version of Safari). In fact, as long as you have not clicked on anything since opening this page, this input box should still be in focus. Now let's implement this function with instructions:


//  Registration 1 Global custom instructions  `v-focus`
Vue.directive('focus', {
 //  When the bound element is inserted into the  DOM  In mid-time … 
 inserted: function (el) {
 //  Focus element 
 el.focus()
 // element-ui
 el.children[0].focus()
 //  Elements have changes, such as show Or the change of parent element can be delayed or judged 
 setTimeout(_ => {
  el.children[0].focus()
 })
 }
})

Related articles: