问题记录
el-input的clear属性 ⬇
➡ 但如果 添加 type="textarea" 属性 后变为文本域 该属性就会失效
解决方案 ➡ 自定义一个图标,为图标绑定事件handleClear
<template>
<div class="textInput">
<el-input ref="ipt"
placeholder="this is a demo"
v-model="localValue"
type="textarea"
@blur="onBlur()"
/>
<i
class="el-icon-circle-close clearButton"
@click="handleClear"
></i>
</div>
</template>
<script>
export default {
name: "index",
data() {
return {
localValue: "",
};
},
methods: {
onBlur() {
console.log("编辑完成,", this.localValue);
},
handleClear() {
if (this.localValue) this.localValue = "";
console.log("clear");
},
},
};
</script>
<style lang="scss" scoped>
.textInput {
position: relative;
box-sizing: border-box;
.clearButton {
position: absolute;
border-radius: 5px;
right: 3px;
z-index: 2;
border: none;
height: 53px;
line-height: 53px;
cursor: pointer;
color: #ccc;
}
.clearButton:hover {
color: #878d99;
}
}
</style>
问题一
如图所示,事件执行顺序为:输入框失焦 -> 再触发点击图标事件,
而我们需要的是,点击图标实现清空内容,同时输入框不会失焦(即不会触发blur事件)
解决
<i
class="el-icon-circle-close clearButton"
@click="handleClear"
@mousedown.prevent
></i>
记录尝试过的方法
<i
class="el-icon-circle-close clearButton"
@click.prevent="handleClear"
></i>
最终实现代码
<template>
<div class="textInput">
<el-input
ref="ipt"
placeholder="this is a demo"
v-model="localValue"
type="textarea"
@blur="onBlur()"
/>
<i
class="el-icon-circle-close clearButton"
@click="handleClear"
@mousedown.prevent
></i>
</div>
</template>
<script>
export default {
name: "index",
data() {
return {
localValue: "",
};
},
methods: {
onBlur() {
console.log("编辑完成,", this.localValue);
},
handleClear() {
if (this.localValue) this.localValue = "";
console.log("clear");
},
},
};
</script>
<style lang="scss" scoped>
.textInput {
position: relative;
box-sizing: border-box;
.clearButton {
position: absolute;
border-radius: 5px;
right: 3px;
z-index: 2;
border: none;
height: 53px;
line-height: 53px;
cursor: pointer;
color: #ccc;
}
.clearButton:hover {
color: #878d99;
}
}
</style>
优化焦点状态
<template>
<div class="textInput">
<el-input
ref="ipt"
placeholder="this is a demo"
v-model="localValue"
type="textarea"
@blur="onBlur()"
@focus="isFocused = true"
/>
<i
class="el-icon-circle-close clearButton"
@click="handleClear"
@mousedown.prevent
></i>
</div>
</template>
<script>
export default {
name: "index",
data() {
return {
localValue: "",
isFocused: false,
};
},
methods: {
onBlur() {
this.isFocused = false;
console.log("编辑完成,", this.localValue);
},
handleClear() {
if (!this.isFocused) {
this.$refs["ipt"].focus();
}
if (this.localValue) this.localValue = "";
console.log("clear");
},
},
};
</script>
<style lang="scss" scoped>
.textInput {
position: relative;
box-sizing: border-box;
.clearButton {
position: absolute;
border-radius: 5px;
right: 3px;
z-index: 2;
border: none;
height: 53px;
line-height: 53px;
cursor: pointer;
color: #ccc;
}
.clearButton:hover {
color: #878d99;
}
}
</style>
记录
这种写法是错误的,因为 ipt 没有被引号包裹,所以 JavaScript 会尝试将其视为一个变量,而不是字符串。如果 ipt 没有在当前作用域中定义为变量,这将导致 ReferenceError。
写为
this.$refs[‘ipt'] or this.$refs.ipt