{{i.vRoleName}}
directives:{
focus: {
inserted: function (el,option) {
var defClass = 'el-input', defTag = 'input';
var value = option.value || true;
if (typeof value === 'boolean')
value = { cls: defClass, tag: defTag, foc: value };
else
value = { cls: value.cls || defClass, tag: value.tag || defTag, foc: value.foc || false };
if (el.classList.contains(value.cls) && value.foc)
el.getElementsByTagName(value.tag)[0].focus();
}
}
}
在Vue中要给input设置焦点,需要注册自定义指令。
由于ElementUI中的el-input是一个自定义组件,并非input元素,所以需要传入组件的class和tag名称来定位组件内的原生input,并调用input的focus方法来获得焦点。
使用的时候,分两种情况:
此时,需要传入class和tag来定位具体的元素
修改指令:兼容ie不支持classList的问题
directives: {
focus: {
inserted: function(el, option) {
var defClass = "el-input",
defTag = "input";
var value = option.value || true;
if (typeof value === "boolean")
value = { cls: defClass, tag: defTag, foc: value };
else
value = {
cls: value.cls || defClass,
tag: value.tag || defTag,
foc: value.foc || false
};
if (!("classList" in document.documentElement)) {
Object.defineProperty(HTMLElement.prototype, "classList", {
get: function() {
var self = this;
function update(fn) {
return function(value) {
var classes = self.className.split(/\s+/g),
index = classes.indexOf(value);
fn(classes, index, value);
self.className = classes.join(" ");
};
}
return {
add: update(function(classes, index, value) {
if (!~index) classes.push(value);
}),
remove: update(function(classes, index) {
if (~index) classes.splice(index, 1);
}),
toggle: update(function(classes, index, value) {
if (~index) classes.splice(index, 1);
else classes.push(value);
}),
contains: function(value) {
return !!~self.className.split(/\s+/g).indexOf(value);
},
item: function(i) {
return self.className.split(/\s+/g)[i] || null;
}
};
}
});
}
if (el.classList.contains(value.cls) && value.foc)
el.getElementsByTagName(value.tag)[0].focus();
}
}
}
补充说明:
在实际用focus指令的过程中,需要给元素添加blur事件:
v-on:blur="focus.count=false"
。失去焦点后一定要把focus指令对应的变量置为false,否则会导致一些不可控的bug。