我是歌谣 代码重构不易 公众号关注小歌谣
前言
网络上流行了一款jq生成月经计算器的代码
是这样的
实现效果如图所示
本次讲解就是说明如何用Vant+jq+Vue实现此代码的重构
先看一眼重构演示的效果 这个是可以直接进行接口调用的
首先我们看一眼目录结构
我们这边贴出我自己手写的代码的核心部分
index.js
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"><!-- 引入样式文件 --><link rel="stylesheet" href="./css/index.css" /><!-- 引入 Vue 和 Vant 的 JS 文件 --><script src="./js/vue.js"></script><script src="./js/vant.js"></script><script type="text/javascript" src="./js/jquery-1.7.2.js"></script><script src="./js/axios.js"></script><script type="text/javascript" src="js/index.js"></script><title>萌芽APP</title><style>body {width: 100%;}.SetTime {width: 100%;height: 40px;background: #F6F7F9;opacity: 1;}span {margin-left: 12px;width: 286px;height: 37px;font-size: 13px;font-family: PingFang SC;font-weight: 400;line-height: 30px;color: #333333;opacity: 1;line-height: 40px;}.SetDate {width: 100%;display: block;}input[type="date"] {box-sizing: border-box;text-align: center;font-size: 1.4em;height: 2.7em;border-radius: 4px;border: 1px solid #c8cccf;color: #6a6f77;-web-kit-appearance: none;-moz-appearance: none;display: block;outline: 0;padding: 0 1em;text-decoration: none;width: 100%;}input[type="date"]:focus {border: 1px solid #ff7496;}input[type="number"] {box-sizing: border-box;text-align: center;font-size: 1.4em;height: 2.7em;border-radius: 4px;border: 1px solid #c8cccf;color: #6a6f77;-web-kit-appearance: none;-moz-appearance: none;display: block;outline: 0;padding: 0 1em;text-decoration: none;width: 100%;}input[type="number"]:focus {border: 1px solid #ff7496;}input[type="button"] {box-sizing: border-box;text-align: center;font-size: 1.4em;height: 2.7em;border-radius: 4px;border: 1px solid #c8cccf;color: #6a6f77;-web-kit-appearance: none;-moz-appearance: none;display: block;outline: 0;padding: 0 1em;text-decoration: none;width: 100%;}.SetButton {width: 50%;left: 25%;margin-top: 20px;text-align: center;}.button{bottom: -100px;display: block;margin: 0 auto;width: 140px;height: 45px;background: #FFA9B5;opacity: 1;border-radius: 78px;border: none;font-size: 17px;font-family: PingFang SC;font-weight: 400;line-height: 5px;color: #FFFFFF;opacity: 1;}.van-picker-column{font-size: 24px;}</style>
</head><body><div id="app" style="position: relative"><div class="SetTime"><span>你最近来月经的日期是</span></div><div class="SetDate"><van-field @focus="SetTimeShow" ref="ScanTextBox" v-model="form.SetTime" placeholder="请输入日期" /></div><van-popup position="bottom" style="width:100%" v-model="show"><van-datetime-picker class="van-picker-column" v-model="currentDate" @confirm="DataSelect" type="date" title="选择年月日" :min-date="minDate" :max-date="maxDate" /></van-popup><div class="SetTime"><span>月经持续天数(天)</span></div><div class="SetDate"><van-field @focus="SetDateShow" ref="ScanTextBox1" v-model="form.KeepTime" placeholder="请输入天数" /></div><div class="SetTime"><span>月经周期(天)</span></div><div class="SetDate"><van-field @focus="SetDateShow1" ref="ScanTextBox2" v-model="form.WeekTime" placeholder="请输入周期" /></div><!-- <button class="button" @click="submit">确定</button>--><!-- <input type="button" style="display: block;width: 100px;height:100px;margin: 0 auto;border-radius: 50%;background: #E7659D;color: white;" value="确定" @click="submit" >--><button class="button" round class="SetButton" type="info" color="#ff7496" @click="submit">确 定</button><van-popup position="bottom" style="width:100%" v-model="show1"><van-picker title="持续天数" show-toolbar class="van-picker-column" :columns="columns" @confirm="onConfirm" @cancel="onCancel" @change="onChange" placeholder="请输入天数" /></van-popup><van-popup position="bottom" style="width:100%;" v-model="show2"><van-picker title="月经周期" class="van-picker-column" show-toolbar :columns="columns1" @confirm="onConfirm1" @cancel="onCancel" @change="onChange" placeholder="请输入天数" /></van-popup><!-- <van-button type="primary" @click="toNotify" class="btn">顶部通知</van-button>--></div>
</body>
<script>// 在 #app 标签下渲染一个按钮组件new Vue({el: '#app',data() {return {minDate: new Date(2020, 0, 1),maxDate: new Date(),currentDate: new Date(),/*定义日期的显示*/show: false,/*定义月经周期的显示*/show1: false,/*定义时间的显示*/show2: false,form: {KeepTime:5,WeekTime:28,SetTime:new Date()},bzDate: '',/*定于月经周期的选择框*/columns1: []/*定义时间周期的选择框*/,columns: [],};},watch: {form: {handler(newName, oldName) {console.log(newName)},immediate: true,deep: true}},created(){var d = new Date();let dateYear = d.getFullYear(); //获取年getAction("/menstrual/historyListByYear"+dateYear).then(res=>{console.log(res,"res")})let dateMonth = d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1; //获取月let dateDate = d.getDate() < 10 ? '0' + d.getDate() : new Date(d).getDate(); //获取当日this.form.SetTime = dateYear + "-" + dateMonth + "-" + dateDatethis.columns=[]this.columns1=[]for(var i=1;i<=90;i++){this.columns.push(i)}console.log(this.columns1,"columns1")for(var i=1;i<=365;i++){this.columns1.push(i)}},methods: {/* toChangeDate(date) {console.log(new Date(date).getFullYear())console.log(new Date(date).getMonth())console.log(new Date(date).getDay())let dateYear = new Date(date).getFullYear(); //获取年let dateMonth = new Date(date).getMonth() + 1 < 10 ? '0' + new Date(e).getMonth() : new Date(e).getMonth(); //获取月let dateDate = new Date(date).getDate() < 10 ? '0' + new Date(e).getDate() : new Date(e).getDate(); //获取当日return dateYear + '-' + dateMonth + '-' +dateDate}, */async submit() {/* let SetTimeOut=new Date(this.form.SetTime)*/await postAction("/menstrual/basicsAddOrUpdate?firstDate=" +this.form.SetTime + "&continuousDays=" + this.form.KeepTime + "&cycleNumber=" + this.form.WeekTime).then(res => {console.log(res)var Request = new Object();Request =this.GetRequest();let token=Request.tokenif (this.noNull(this.form.SetTime) && this.noNull(this.form.KeepTime) && this.noNull(this.form.WeekTime)) {
/*http://114.215.149.84:8086/*/window.location.href = "./index.html?lastDate=" + this.bzDate + "&keepDate="+ this.form.KeepTime + "&weekDate=" + this.form.WeekTime+"&token="+token;} else {this.$toast.success("当前所填项不能为空")}})},toNotify() {},/*点击确定之后触发的点击事件*/GetRequest() {var url = location.search; //获取url中"?"符后的字串var theRequest = new Object();if (url.indexOf("?") != -1) {var str = url.substr(1);strs = str.split("&");for(var i = 0; i < strs.length; i ++) {theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);}}return theRequest;},onConfirm(value, index) {console.log(value)this.form.KeepTime = valuethis.show1 = false},/*点击确定之后触发的点击事件*/onConfirm1(value, index) {console.log(value)this.form.WeekTime = valuethis.show2 = false},onChange(picker, value, index) {},/*定义显示弹出框的方法*/SetDateShow() {this.$refs.ScanTextBox1.readonly='readonly';setTimeout(() => {this.$refs.ScanTextBox1.readonly=null;}, 200);console.log(11111)this.show1 = true},/*定于显示弹出框的方法*/SetDateShow1() {this.$refs.ScanTextBox2.readonly='readonly';setTimeout(() => {this.$refs.ScanTextBox2.readonly=null;}, 200);this.show2 = true},onCancel() {this.show = falsethis.show1 = falsethis.show2 = false},/*定于显示弹出框的方法*/SetTimeShow() {this.$refs.ScanTextBox.readonly='readonly';setTimeout(() => {this.$refs.ScanTextBox.readonly=null;}, 200);this.show = true},/* 执行日期的回调函数 处理日期的回调函数*/DataSelect(e) {var d = new Date(e);var datetime = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();/* console.log(e)console.log(e.getFullYear()) */let dateYear = e.getFullYear(); //获取年let dateMonth = e.getMonth() + 1 < 10 ? '0' + (e.getMonth() + 1) : e.getMonth() + 1; //获取月let dateDate = e.getDate() < 10 ? '0' + e.getDate() : new Date(e).getDate(); //获取当日this.form.SetTime = dateYear + "-" + dateMonth + "-" + dateDatethis.bzDate = e;this.show = false},noNull(x) {if (x === "" || x === undefined || x === null) {return false;}return true;}/* timestampToDate(timestamp) {let data = new Date();data.setTime(timestamp * 1000)return data} */},});// 调用函数组件,弹出一个 Toast// 通过 CDN 引入时不会自动注册 Lazyload 组件// 可以通过下面的方式手动注册/* Vue.use(DatetimePicker);*//* let lastDate = document.getElementById("lastDate").value;let keepDate = $("#keepDate").val()let weekDate = $("#keepDate").val() *//* function upperCase(x) {var y = document.getElementById(x).valuelastDate = y;}function upperKeepDate(x) {var y = document.getElementById(x).valuekeepDate = y;}function upperWeepDate(x) {var y = document.getElementById(x).valueweekDate = y;}$("#thisOk").click(function() {console.log(1);console.log(lastDate);console.log(keepDate);console.log(weekDate);if (noNull(lastDate) && noNull(keepDate) && noNull(weekDate)) {window.location.href = "../index.html?lastDate=" + lastDate + "&keepDate=" + keepDate + "&weekDate=" + weekDate;} else {alert("请输入正确得值")}});function noNull(x) {if (x === "" || x === undefined || x === null) {return false;}return true;}*/
</script></html>
<!DOCTYPE html>
<html><head><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>萌芽App</title><link type="text/css" rel="stylesheet" href="css/public_v2.css" /><link type="text/css" rel="stylesheet" href="css/base.css" /><link type="text/css" rel="stylesheet" href="css/blue.css" /><link href="css/userLogin.css" rel="stylesheet" type="text/css" /><script type="text/javascript" src="js/jquery-1.7.2.js"></script><script type="text/javascript" src="js/newfemale.js"></script><script language='javascript' src="js/userLogin.js"></script><meta http-equiv="Cache-Control" content="no-transform" /><link rel="stylesheet" href="./css/index.css" /><!-- 引入 Vue 和 Vant 的 JS 文件 --><script src="./js/vue.js"></script><script src="./js/vant.js"></script><script src="./js/axios.js"></script><script type="text/javascript" src="./js/index.js"></script></head><body><INPUT style="DISPLAY: none" id=nowElement type=hidden><div class="wrapper"><!-- header end --><!-- main --><div class="main"><div class="mod_2b"><!--控制标题的数据--><!--<h2>女性月经周期与排卵期计算器</h2>--><!--<div class="health clearfix">--><div class="mod_1b mod_safe"><div style="display: none" class="time_lag clearfix"><span>平常两次月经大概相隔:</span><a class="minus" onclick='female.fallOff();'></a><input type="text" id='minMensesPriod' readonly value="28" /><!-- <INPUT type='hidden' id=minMensesing class=circleCss value=5>--><a onclick='female.increase();' class="plus"></a><span>月经期时间:</span><a class="minus" onclick='female.fallOff2();'></a><INPUT type='type' id=minMensesing class=circleCss value=5><a onclick='female.increase2();' class="plus"></a><a onclick='female.creset();' id='acrest' class="again">重新测试</a></div><div class="safe_detail" id='womensafeDateCon'><div class="safe_calendar" id='chosecal'><span class="date_first" id='popCss'>请点击选择月经第一天</span><div class="date_select"><span class="year" id="leftYear">2012</span><b>年</b><!--<a href='javascript:void(0);' id='yearLink'></a>--><span id='leftMonth' class="month">10月</span><b>月</b><!--<a href='javascript:void(0);' id='monthLink' class=""></a>--></div><!--处理li的逻辑--><ul class="date_detail" id='leftTable'><li class="week">周日</li><li class="week">周一</li><li class="week">周二</li><li class="week">周三</li><li class="week">周四</li><li class="week">周五</li><li class="week">周六</li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li></ul></div><div class="safe_calendar safe_calendar_right" id='rightCal' style="clear: both"><div class="date_select"><span class="year" id='rightYear'>2012</span><b>年</b><a href='javascript:void(0);' id="rYearLink" class="link"></a><span class="month" id='rightMonth'>10</span><b>月</b><a href='javascript:void(0);' id="rMonthLink" class="link"></a></div><ul class="date_detail" id='rightTable'><li class="week">周日</li><li class="week">周一</li><li class="week">周二</li><li class="week">周三</li><li class="week">周四</li><li class="week">周五</li><li class="week">周六</li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li></ul></div></div></div><div style="clear: both"></div><ul class="safe_calendar_tips" style="width: 100%;height: 100px"><!--<li style="display: none" id="aZlue"><em class="aBlue"></em>所选日期</li><li style="display: none" id="aBlue"><em class="aBlue"></em>所选日期</li>--><li style="float: left;" id="aYellow"><em style="float:left;width: 11px;margin-top: 4px;height: 11px;border-radius: 11px;line-height: 66px;font-size: 12px" class="aYellow"></em><p style="float: left;font-size: 12px;">月经期</p></li><li style="float: left;" id="aRed"><em style="float:left;margin-top: 4px;margin-left:5px;width: 11px;height: 11px;border-radius: 11px;line-height: 66px;font-size: 12px" class="aRed"></em><p style="float: left;font-size: 12px;">排卵期</p></li><li style="float: left;" id="aGreen"><em style="float:left;margin-left:5px;margin-top: 4px;width: 11px;height: 11px;border-radius: 11px;line-height: 66px;" class="aGreen"></em><p style="float: left;font-size: 12px;">安全期</p></li></ul></div></div></div><div id="app" style="clear: both;position: fixed;bottom: 0;width: 100%;opacity: 0.8;"><van-cell-group><van-switch-cell size="24px" :active-value="active" active-color="#FFA9B5" inactive-color="#FFA9B5" v-model="checked" @change="ChangeStatus" title="大姨妈来了" /></van-cell-group><!--<van-cell is-link @click="showPopup">展示弹出层</van-cell>--><van-popup v-model="show" position="bottom"><van-datetime-picker @cancel="onCancel" @confirm="onConfirm" v-model="currentDate" type="date" title="选择年月日" :min-date="minDate" :max-date="maxDate" /></van-popup></div><!--<div id="abc" style="width: 100px;height:200px;border:1px solid red"></div>--><!--<div style="text-align:center;margin:50px 0; font:normal 14px/24px 'MicroSoft YaHei';">
<p>适用浏览器:IE8、360、FireFox、Chrome、Safari、Opera、傲游、搜狗、世界之窗.</p>
<p>来源:<a href="http://down.admin5.com/info/" target="_blank">A5源码</a></p><br>
</div>--></body></html>
<script>$(function() {var Query = $('.date_detail a').children().text()var list = $('.date_detail')$('.link').each(function() {//console.log(this,'123456')console.log($(this).attr('class'))})/* console.log(list,"dssdds ");$('[!aYellow]').css('display','none');*//*for (let i = 0; i <Query.length ; i++) {var li = Query[i]var $aa = $(li).find("a")console.log($aa,"+++++");console.log($aa.get(0),"=====");}*/console.log(Query, "Query")console.log(document.body.clientWidth, "clientWidth")console.log("------------")console.log(document.body.clientWidth == 414, "clientWidth")console.log("------------")if (300 < document.body.clientWidth && document.body.clientWidth < 350) {$('.date_detail li').css("margin-left", '3px');$('.date_detail li').addClass("geyao");} else if (350 < document.body.clientWidth && document.body.clientWidth < 400) {$('.date_detail li').css("margin-left", '8px');$('.date_detail li').addClass("geyao");} else if (400 < document.body.clientWidth && document.body.clientWidth < 430) {$('.date_detail li').css("margin-left", '15px');$('.date_detail li').addClass("geyao");}let aGeyao = document.getElementsByClassName('geyao')/* console.log($(".geyao a"))$(".geyao a").each(function(){console.log($(this).addClass('geyao'))});*//*console.log(Query,"Query")*/});var lastTime = null;let map_callback = (self) => {console.log(self.lastTime, "abssddsdsd")lastTime = self.lastTime;var m = new Date(lastTime).getMonth();var y = new Date(lastTime).getFullYear();calendar.show(y, m, null)female.calculate(new Date(lastTime).getTime());}new Vue({el: '#app',data() {return {active: '是',checked: false,show: false,minDate: new Date(2020, 0, 1),maxDate: new Date(),currentDate: new Date(),lastTime: '',/*存储数据的数据结构*/cycleNumber: 0,continuousDays: 0,SetTime: '',/*传入id*/SetId: '',endTime: '',SetTime1: '',};},methods: {formatter(type, val) {if (type === 'month') {return `${val}月`;} else if (type === 'day') {return `${val}日`;}return val;},onCancel() {this.checked = falsethis.show = false},async historyListByYear(dateYear) {await getAction("/menstrual/historyListByYear?year=" + dateYear).then(res => {console.log(res, "LastYear")if (res.data.code = 200) {let {cycleNumber,continuousDays} = res.data.result.userMenstrualBasics;this.cycleNumber = cycleNumberthis.continuousDays = continuousDaysconsole.log(cycleNumber, 'cycleNumber');console.log(continuousDays, "continuousDays");}})},async historyAdd() {await postAction("/menstrual/historyAdd?startTime=" + this.SetTime).then(res => {if (res.data.code = 200) {console.log(res, "result")this.SetId = res.data.result.idconsole.log(this.SetId, "SetId")this.historyEdit(this.SetId)}})},async historyEdit(id) {await postAction("/menstrual/historyEdit?endTime=" + this.SetTime1 + "&id=" + id).then(res => {if (res.data.code = 200) {/*let myDate = new Date();
myDate.setDate(myDate.getDate()+5)*/console.log(this.endTime, "endTime");console.log(res, "操作成功")}})},onConfirm(e) {let dateYear = e.getFullYear(); //获取年let dateMonth = e.getMonth() + 1 < 10 ? '0' + (e.getMonth() + 1) : e.getMonth() + 1; //获取月let dateDate = e.getDate() < 10 ? '0' + e.getDate() : new Date(e).getDate(); //获取当日this.SetTime = dateYear + "-" + dateMonth + "-" + dateDate/*控制日期参数*/this.historyListByYear(dateYear)/*let LastYear=e.getFullYear()*/console.log("我进来了")/* new Date(( new Date()).getTime()+1000*60*60*24);*//*dateTime.setDate(dateTime.getDate()+1);*//* let data=new Date(e.getTime()+(1000*60*60*this.cycleNumber));*//*let data=e*/this.historyAdd()var data = econsole.log(this.continuousDays, "continuousDays")data = data.setDate(data.getDate() + this.continuousDays);data = new Date(e);console.log(data, "data")let dateYear1 = data.getFullYear(); //获取年console.log(dateYear1, "dateYear1")let dateMonth1 = data.getMonth() + 1 < 10 ? '0' + (data.getMonth() + 1) : data.getMonth() + 1; //获取月console.log(dateMonth1, "dateMonth1")let dateDate1 = data.getDate() < 10 ? '0' + data.getDate() : new Date(data).getDate(); //获取当日console.log(dateDate1, "dateDate1")this.SetTime1 = dateYear1 + "-" + dateMonth1 + "-" + dateDate1console.log(this.SetTime1, "SetTime1")console.log(this.SetId, "SetId")console.log("我出去了")this.checked = falsethis.show = falsethis.lastTime = e;map_callback(this)},ChangeStatus() {this.show = true;},/* timestampToDate(timestamp) {let data = new Date();data.setTime(timestamp * 1000)return data} */},});/* var lastDate = nullvar keepDate = null;var weekDate = null;$(document).ready(function (){function GetRequest() {var url = location.search; //获取url中"?"符后的字串var theRequest = new Object();if (url.indexOf("?") != -1) {var str = url.substr(1);strs = str.split("&");for(var i = 0; i < strs.length; i ++) {theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);}}return theRequest;}var Request = new Object();Request = GetRequest();lastDate = Request.lastDate;keepDate = Request.keepDate;weekDate = Request.weekDateconsole.log(lastDate);console.log(keepDate);console.log(weekDate);})*/window.onload = function() {document.querySelectorAll('a').forEach(a => {if (a.className == '') {a.style.display = 'none'}})}
</script>
我是歌谣,放弃 很难 坚持一定很酷