前端vue实现手机号输入框下拉展示历史登录过的手机号码

24 篇文章 0 订阅

在这里插入图片描述
需求:做一个登录页面,登录过的号码显示在下拉框,下次登录可以选择登录过的号码进行登录无需重新输入。

样式就不附上了,记录下逻辑过程吧
大概就是在输入号码点击登录的时候,localstorage记录下手机号码,每次打开登录页面的时候先取localstorage里面的手机号码作为历史手机号下拉框的内容

<template>
<div>
	<div>
		<input @focus="phoneFocus" @blur="phoneBlur" @input="phoneChange" placeholder="请输入手机号码" maxlength="11" v-model="phone"></input>
		<div v-if="showHistory && historyPhones.length">
			<p v-if="item in historyPhones"  :key="item" @mousedown="thisPhone(item)">{{item}}</p>
			<p @mousedown="clearAll">清除所有记录</p>
		</div>
	</div>
	<div @click="login">登录</div>
</div>
</template>

<script>
export default({
	data(){
		return{
			phone:"",
			showHistory:false,
			historyPhones:[],
			
		}
	},
	mounted(){
	let list = localStorage.getItem("historyPhones")
      ? JSON.parse(localStorage.getItem("historyPhones"))
      : [];
    this.historyPhones = list.splice(0, 5);
	
	},
	methods:{
		login(){
			let curIndex = this.historyPhones.indexOf(phoneNum);
			//先判断原本的历史手机号码是否存在
			if (curIndex > -1) {
				//如果存在,把它放到最前面
			   this.historyPhones.splice(curIndex, 1);
			   this.historyPhones.unshift(phoneNum);
			 } else {
			 	//如果不存在,添加在历史手机号码数组第一位
			   this.historyPhones.unshift(phoneNum);
			 }
			this.historyPhones = this.historyPhones.splice(0, 5);
			//只取五条数据,不建议展示过多
			localStorage.setItem("historyPhones", JSON.stringify(this.historyPhones));
			//存在localstorage
			
		},
		phoneChange() {
		    if (this.phone.length < 11) {
		      this.showHistory = true;
		    } else {
		      this.showHistory = false;
		    }
		  },
		phoneFocus() {
		    this.showHistory = true;
		},
		phoneBlur() {
		 this.showHistory = false;
		},
		thisPhone(phoneNum){
			this.phone = phoneNum;
			this.$nextTick(() => {
			   this.showHistory = false;
			 });
		},
		clearAll(){
			localStorage.removeItem("historyPhones");
      		this.historyPhones = [];
		}
	}
})
</script>

这里面有一个细节就是点击历史手机号或者点击清除历史记录的时候,我用的是mousedown,因为点击的时候希望同时收起下拉框,如果用click的话,容易触发input的blur事件,会快一步把下拉框收起来以至于点不到我们想点的历史手机号码,这个涉及到click和mousedown的执行顺序。
click:当鼠标指针停留在元素上方,然后按下并松开鼠标左键时,就会发生一次 click 事件。
mousedown:当鼠标指针移动到元素上方,并按下鼠标按键(左、右键均可)时,会发生 mousedown 事件。
因此在这里用 mousedown 代替 click

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值