准备图标或者图片
<el-input>标签代码
<el-input ref="pwdInput":type="pwdObj.pwdType"v-model="password"@focus="focusEnd($event)"><!-- input中加图标必须要有slot="suffix"属性,不然无法显示图标 --><el-image slot="suffix"class="img-sty":src="getIconUrl(pwdObj.pwdType === 'text' ? 'offeye' : 'openeye')"fit="scale-down"@click="changeye('pwdType', 'pwdInput')" /></el-input>
<script type="text/javascript">中代码
<script>export default {data() {return {password: '',pwdObj: { pwdType: 'password'}}},computed: {// 获取图标getIconUrl() {return function (name, type = 'svg') {return require(`@/assets/img/icons/${name}.${type}`)}},methods: {//点击图标控制密码的显示和隐藏changeye(typeName, refName) {this.$set(this.pwdObj,`${typeName}`,this.pwdObj[`${typeName}`] === 'password' ? 'text' : 'password')this.$refs[`${refName}`].focus()},//点击查看密码图标使光标定位到最后focusEnd(e) {//input获取光标显示在最后const obj = e.srcElement,// obj.focus()len = obj.value.length//光标定位要加上 setTimeOut,不然就会重新光标定位失败setTimeout(() => {obj.selectionStart = obj.selectionEnd = len}, 60)}}}</script>
可能自定义图标后,显示的位置没那么准确,根据需要通过css调整
.img-sty {cursor: pointer;margin-top: 10px;}
最终效果