在Vue中要給input設置焦點,需要注冊自定義指令。
main.js中
Vue.directive('focus', function (el, option) { var defClass = 'el-input', defTag = 'input'; var value = option.value || true; if (typeof value === 'boolean')//頁面中只有一個組件用到v-focus指令 v-focus='true' value = { cls: defClass, tag: defTag, foc: value }; else//頁面有多個組件用到v-focus指令 value = { cls: value.cls || defClass, tag: value.tag || defTag, foc: value.foc || false }; if (el.classList.contains(value.cls) && value.foc)//當頁面中包含defclass,且foc屬性為true時 el.getElementsByTagName(value.tag)[0].focus();//設置tag的第一個元素聚焦 });
由於ElementUI中的el-input是一個自定義組件,並非input元素,所以需要傳入組件的class和tag名稱來定位組件內的原生input,並調用input的focus方法來獲得焦點。
頁面中只有一個組件用到focus指令
<el-input v-focus="true"></el-input>
頁面中有多個組件用到focus指令,需要傳入class和tag來定位具體的元素
<el-input v-focus="{cls: 'el-input',tag: 'input', foc:focususername}" v-on:blur="focususername=false" placeholder="請輸入用戶名"></el-input> <el-input v-focus="{cls: 'el-input',tag: 'input', foc:focususerpwd}" v-on:blur="focususerpwd=false" placeholder="請輸入密碼"></el-input>
export default { name: "Login", data() { return { focususername: true, focususerpwd: true, }; }, }