Vue事件,树形结构处理,字符串截取,以及js时间处理
1. vue父组件中触发子组件事件
- 父组件
- 子组件
2. 子组件调用父组件的事件
- 直接在子组件中通过this.$parent.event来调用父组件的方法
2. 在子组件里用$emit向父组件触发一个事件,父组件监听这个事件
3.父组件把方法传入子组件中,在子组件里直接调用
4. Vue 三种带文字分割线实现方式
4.1 第一种利用::before
和 ::after
实现
效果:
代码如下:
.not_has_more {
margin: 10px 0;
line-height: 50px;
// text-align: center;
position: relative;
height: 33px;
font-size: 15px;
font-family: PingFangSC-Regular, PingFang SC;
font-weight: 400;
color: rgba(140, 142, 165, 1);
line-height: 33px;
span {
margin-left: 110px;
}
&::after {
position: absolute;
width: calc(100% - 210px);
height: 0.5px;
background: #dadada;
content: '';
top: 15px;
right: 0;
}
&::before {
position: absolute;
width: 100px;
height: 0.5px;
background: #dadada;
content: '';
top: 15px;
left: 0;
}
4.2 第二种 利用 background
和flex
叠加实现
html:
<div class="divider_self">
<div class="txt">常用品牌</div>
</div>
css:
.divider_self {
margin: 36px auto 35px;
width: 324px;
background-color: #e6e6e6;
height:.7px;
position: relative;
@include flex;
.txt {
width: 144px;
height: 24px;
font-size: 24px;
font-family: PingFangSC-Regular, PingFang SC;
font-weight: 400;
color: #8c8ea5;
line-height: 24px;
background-color: #ffffff;
text-align: center;
}
}
4.3 第三种 使用第三方UI库 vant的组件
<Divider class="divider_cp"> 常用品牌 </Divider>
.divider_cp {
margin: 24px auto 25px;
width: 324px;
background: #ffffff;
border-radius: 24px;
border-color: #e6e6e6;
padding: 0 16px;
font-size: 24px;
font-family: PingFangSC-Regular, PingFang SC;
font-weight: 400;
color: #8c8ea5;
line-height: 24px;
}
5.获取当月的月份,第一天,最后一天
在获取之前,需要先明白以下几个方法
var d = new Date();
d .getFullYear(); //获取完整的年份(4位)
d .getMonth(); //获取当前月份(0-11,0代表1月)
d .getDate(); //获取当前日(1-31)
d .getDay(); //获取当前星期X(0-6,0代表星期天)
d .getTime(); //获取当前时间(从1970.1.1开始的毫秒数)
d .getHours(); //获取当前小时数(0-23)
d .getMinutes(); //获取当前分钟数(0-59)
d .getSeconds(); //获取当前秒数(0-59)
d .getMilliseconds(); //获取当前毫秒数(0-999)
d .toLocaleDateString(); //获取当前日期
var mytime=d.toLocaleTimeString(); //获取当前时间
d.toLocaleString( ); //获取日期与时间
5.1 padStart()
ES2017 引入了字符串补全长度的功能。如果某个字符串不够指定长度,会在头部或尾部补全。
padStart()
用于头部补全,padEnd()
用于尾部补全。
'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'
'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'
5.2 getDate()
getDate() 方法可返回月份的某一天。
console.log("date.getDate()", date.getDate());//当天几号,比如4号
let hao = new Date(2023, 6, 0).getDate()
console.log("2023年6月的最后一天为", hao);//30号
5.3 最终代码
// / type=0 第一天; 1 最后一天; 不传当天;
function getCurMonthFirstOrLast(type = 2) {
let date = new Date;
// date.getFullYear() 获取当年
console.log("date", typeof date.getFullYear());//number类型,
let y = date.getFullYear().toString();//加上.toString()转化成字符串
console.log("y", y);//2023
console.log("月份", (date.getMonth() + 1).toString().padStart(2, 0));
let m = (date.getMonth() + 1).toString().padStart(2, 0);
console.log("m", m);//08
console.log("new Date(y, m, 0)", new Date(y, m, 0).getDate());//当前月份的最后一天是几号
console.log("date.getDate()", date.getDate());//当天几号
let d = (['1', new Date(y, m, 0).getDate(), date.getDate()][type]).toString().padStart(2, 0);
console.log("d", d);//当天日期如4号
return [y, m, d].join("-");
}
let time = getCurMonthFirstOrLast();
console.log(time);
6. 截取字符串第n个逗号之前
在此之前需要明白js中的indexOf
的用法
6.1 indexOf() 方法
- indexOf() 方法可返回数组中某个指定的元素位置。 该方法将从头到尾地检索数组,看它是否含有对应的元素。
- 开始检索的位置在数组 start 处或数组的开头(没有指定 start参数时)。如果找到一个 item,则返回 item 的第一次出现的位置。
- 如果在数组中没找到指定元素则返回 -1。
例子:
//数组语法
// array.indexOf(item,start)
//item 必须 要查找的元素的位置,
//start 非必须可选的整数参数。规定在数组中开始检索的位置。
//它的合法取值是 0 到 stringObject.length - 1。如省略该参数,则将从字符串的首字符开始检索。
let food= ["番茄", "胡萝卜", "排骨", "苹果"];
let a = food.indexOf("苹果");
console.log(a) // 3
let b= food.indexOf("香蕉");
console.log(b) // -1
//字符串语法
//string.indexOf(value,start)
// value 必须 要查找的元素的位置
// start 可选的整数参数。规定在字符串中开始检索的位置。它的合法取值是 0 到 string.length - 1。如省略该参数,则将从字符串的首字符开始检索。
let str="Hello world!";
console.log(str.indexOf("Hello"));//0
console.log(str.indexOf("World") );//-1
console.log(str.indexOf("world"));//6
6.2 substring() 方法
substring() 方法返回的子串包括 开始 处的字符,但不包括 结束 处的字符。
string.substring(from, to)
参数 | 描述 |
---|---|
from | 必需。一个非负的整数,规定要提取的子串的第一个字符在 string Object 中的位置。 |
to | 可选。一个非负的整数,比要提取的子串的最后一个字符在 string Object 中的位置多 1。 如果省略该参数,那么返回的子串会一直到字符串的结尾。 |
6.3 最终实现
// str 表示传入的字符串,n表示要查找的第几个字符
function getSubstringBeforeNthComma(str, n) {
let count = 0;
let index = -1;
// str.indexOf(",", index + 1))表示查找去"," 从第0个位置开始找
while (count < n && (index = str.indexOf(",", index + 1)) !== -1) {
count++;
}
return index === -1 ? str : str.substring(0, index);
}
// 示例用法:
const str = "a,b,c,d,e, f,g,h";
const n = 3;
const sub = getSubstringBeforeNthComma(str, n);
console.log(sub); // 输出"a,b,c"
7. js获取本月的所有周六周末
function getDay() {
let date = new Date()
let year = date.getFullYear()
let month = date.getMonth()
let allDay = new Date(year, month + 1, 0).getDate() //获取当月总天数
let saturday = []; //周六
let sunday = []; //周日
for (let i = 1; i <= allDay; i++) {
let week = new Date(year, month, i).getDay()
let str = `${year}-${(month + 1) < 10 ? '0' + (month + 1) : (month + 1)}-${i < 10 ? '0' + i : i}`
if (week === 0) {
sunday.push(str)
} else if (week === 6) {
saturday.push(str)
}
}
return { sunday, saturday }
}
const { sunday, saturday } = getDay()
console.log(sunday, saturday);
8. 设置字段控制表格状态
- 给每一条数据添加字段
2. 控制状态,显示隐藏
3. 编辑,确定状态控制
handleEdit(row) {
console.log(row);
if (row.Iseditor) {
this.$set(row, 'Iseditor', false)
} else {
this.$set(row, 'Iseditor', true)
}
},
confirmSelect(row) {
if (row.Iseditor) {
this.$set(row, 'Iseditor', false)
} else {
this.$set(row, 'Iseditor', true)
}
},
9. 将数组数据转换成树结构
- 对数据进行分析
2. 完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const CurrentPageData = [
{
"FaultTypeId": 1,
"FaultTypeName": "A 一级",
"FaultParTypeId": 0,
"ISFaultTypeOFF": false,
},
{
"FaultTypeId": 2,
"FaultTypeName": "A-1 二级",
"FaultParTypeId": 1,
"ISFaultTypeOFF": false
},
{
"FaultTypeId": 6,
"FaultTypeName": "B 一级",
"FaultParTypeId": 0,
"ISFaultTypeOFF": false
},
{
"FaultTypeId": 7,
"FaultTypeName": "B-2 二级",
"FaultParTypeId": 6,
"ISFaultTypeOFF": false
},
{
"FaultTypeId": 8,
"FaultTypeName": "新建子节点热帖",
"FaultParTypeId": 1,
"ISFaultTypeOFF": false
}
];
let tree_data = [];
CurrentPageData.forEach((item) => {
tree_data.push({
id: item.FaultTypeId,
title: item.FaultTypeName,
pid: item.FaultParTypeId,
gid: item.ISFaultTypeOFF,
})
})
console.log("tree", tree_data);
// 对数据进行递归的排序添加
function objToTree(treeList, root) {
const arr = []
// 1.遍历
treeList.forEach((item) => {
// console.log("item1",item);
// 2.首次传入pid为0 判断treeList的pid是否为0 如果为空就是一级节点
if (item.pid === root) {
// 找到之后就要去找item下面有没有子节点 以 item.id 作为 父 id, 接着往下找
const child = objToTree(treeList, item.id)
///console.log('子节点查询:', item.pid, item.title, child);
if (child.length > 0) {
// 如果child的长度大于0,说明找到了子节点
item.child = child
}
// 将item项, 追加到arr数组中
// console.log("item2",item);
arr.push(item)
}
})
return arr
}
let arree = objToTree(tree_data, 0);
console.log("arree",arree);
</script>
</body>
</html>
10. 根据树的节点获取树对应的名称
getCascaderObj(val, opt) {
return val.map(function (value, index, array) {
for (var itm of opt) {
if (itm.value == value) { opt = itm.children; return itm; }
}
return null;
});
},
注:for…of
它是ES6中新增加的语法,用来循环获取一对键值对中的值
- 循环一个数组
js
复制代码
let arr = ['China', 'America', 'Korea']
for (let o of arr) {
console.log(o) //China, America, Korea
}
11. 日期格式相关转换
11.1 中国标准时间转换
//date:Wed Apr 20 2022 00:00:00 GMT+0800 (中国标准时间)
let start = this.dateFormat('yyyy-MM-dd hh:mm:ss', date)
//this.dateFormat()方法
dateFormat(fmt, date) {
let o = {
"M+": date.getMonth() + 1, //月份
"d+": date.getDate(), //日
"h+": date.getHours(), //小时
"m+": date.getMinutes(), //分
"s+": date.getSeconds(), //秒
"q+": Math.floor((date.getMonth() + 3) / 3), //季度
"S": date.getMilliseconds() //毫秒
}
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)))
return fmt
},
console.log(start)
//2022-04-20 00:00:00
11.2 时间戳转换
//时间戳
let timestamp=1650505881000
let date2 = this.calculateLiveTime(timestamp)
//this.calculateLiveTime(timestamp)方法
calculateLiveTime(timestamp) {
let date = new Date(timestamp);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
let Y = date.getFullYear() + '-';
let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
let s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
let strDate = Y + M + D + h + m + s;
return strDate;
},
console.log(date2 )
//2022-04-21 09:51:21
11.3 获取今天,明天
//今天
let today=new Date()
//Fri Apr 22 2022 17:37:17 GMT+0800 (中国标准时间)
//明天
let day2=new Date()
day2.setTime(day2.getTime() + 24 * 60 * 60 * 1000);
console.log(day2)
//Sat Apr 23 2022 17:38:35 GMT+0800 (中国标准时间)
转载自:https://juejin.cn/post/7277797749893382185