vue基于input实现密码的显示与隐藏功能
前言
大家都知道,一般情况下,输入框的密码我们是看不到密码的,只有当我们点击查看密码的小图标时,密码才会显现出来,实现起来也非常简单,通过点击图标让input的type属性变化即可。但是隐藏的密码一般是 "•" 展示,那我们想要用 "*" 或者其他的符号显示该怎么办呢,今天就教大家用其他的符号代替 "•" 在密码隐藏时展示。
实现效果
实现思路
1.首先我们要先在data中定义一个变量用来控制小图标的显示与隐藏; 2.在页面中循环遍历data中的privates(密钥内容),拿到字符串的长度length; 3.拿到密钥的长度后,先把它分割成字符串数组,用于后面插入; 4.然后通过splice方法插入到字符串数组中,splice有三个参数,第一个参数是必要的,是插入元素的位置,第二个参数的意思是要插入的元素数量,第三个参数的意思是要插入的元素是什么; 5.最后我们将字符串数组通过join方法转换成字符串即可。
话不多说,直接上实例代码
<template> <div class="private"> <!--// 显示内容: ==0时显示*,==1时显示密钥内容 --> <span v-if="codeType == 1">{ { privates}}</span> <span class="special" v-if="codeType == 0">{ { star}}</span> <!--// 小图标: ==0时展示隐藏图标,==1时展示显示图标--> <span v-if="codeType == 1"><img @click="reveal" src="https://s4.ax1x.com/2022/01/07/79E7dg.png"></span> <span v-if="codeType == 0"><img @click="conceal" src="https://s4.ax1x.com/2022/01/07/79EOWn.png"></span> </div> </template> <script> export default { data() { return { privates: "dhwiglfliagw5f34a1w3w54f", //密钥内容 codeType: 0, //控制密钥显示隐藏 等于1时显示,等于0时隐藏 star: "", //要插入的星星* } }, mounted() { // 循环遍历拿到密钥的长度 for (var i = 0; i < this.privates.length; i++) { let star = this.star.split() //分割成字符串数组 star.splice(i, i, *) //添加到数组 this.star = star.join() //将数组转换为字符串 } }, methods: { //显示事件 reveal() { this.codeType = 0 }, //隐藏事件 conceal() { this.codeType = 1 }, } } </script> <style scoped> .private { display: flex; align-items: center; } .private img { width: 20px; height: 20px; vertical-align: middle; cursor: pointer; margin-left: 9px; } .special { position: relative; top: 4px; } </style>
至此这个小功能就实现啦!