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