一 判断元素是否为空
// 我们可以用这方法判断if (props.query !== '' && props.termId !== '' && props.label !== '' && props.token !== '')这种情况
const filterIt = (arr) => {
let status = true;
arr.forEach((element) => {
if (['',null].includes(element)) {
status = false;
}
return status;
});
};
我们需要检查对象是否为空,我们可以使用如下:
Object.keys({}).length // 0
Object.keys({key: 1}).length // 1
Object.keys() 方法用于获取对象的键并返回包含这些键值的数组。如果返回的数组长度为 0,则对象必须为空。
二 ES6结构语法
根据经验,尽量将函数参数的数量限制在 2 个或最多 3 个。如果它需要这么多参数,则可能是你的函数做的太多了。但是,如果仍然需要它,请使用 JavaScript 对象作为参数。为了使函数期望的属性变得明显,可以使用 ES6 解构语法。
function createMenu({ title, body, buttonText, cancellable }) {
// ...
}
createMenu({
title: "Foo",
body: "Bar",
buttonText: "Baz",
cancellable: true
});
三 this.$nextTick的使用
this.$nextTick是等待页面数据渲染完毕才会执行,我们可以这样用:
data() {
return {
info: { 1: 1, 2: 2, 3: 3 },
content: this.$nextTick(() => {
this.content = this.info;
}),
};
},
以此可以达到原本mounted生命周期钩子函数中操作页面数据的效果
四 ES6常用方法总结
// 返回的是对象键值对组成的数组
console.log(Object.entries(this.content));
// 返回的是对象的键
console.log(Object.keys(this.content));
// 返回的是对象的值
console.log(Object.values(this.content));
// 遍历
Object.entries(this.content).forEach((val) => {
console.log(`${val[0]}:${val[1]}`);
});
// 正确遍历
for (let [key, val] of Object.entries(this.content)) {
console.log(key, val);
}
const arr = [1, 2, 3, 6, 6, 6];
// 查找元素
console.log(
"=============>",
arr.find((item) => item === 6)
);
// 查找元素下标
console.log(
"======================>",
arr.findIndex((item) => item === 6)
);
// 查找每一项是否符合要求
console.log(
"查",
arr.every((item) => item > 2)
);
// 深拷贝
console.log("======================>", Array.of(...arr));
const array = [...arr, [0, 9, 8]];
console.log(
"======================>reduce二维数组转一维",
array.reduce((val, ele) => {
return val.concat(ele);
}, [])
);
const arrays = [...array, [1, 2, [0]]];
console.log(
"======================>多维转一维",
arrays.join(",").split(",")
);
console.log(
"======================>reduce使用",
arr.reduce((val, ele) => {
if (ele in val) {
val[ele + ""]++;
} else {
val[ele + ""] = 1;
}
return val;
}, {})
);
this.$nextTick(() => {
this.info = [4, 56, 3, 3, 3];
// 去重
console.log(Array.from(new Set(this.info)), 1e8);
});
let person = () => ({
age: 20,
addr: "Beijing City",
});
// 箭头函数返回对象
console.log(person());
// 对比对象的值是否相等
console.log(Object.is(this.content, person));
// assign合并对象
var obj = { a: 1, b: 2 };
var copy = Object.assign({ c: 3 }, obj);
console.log(copy);
vue的computed和watch钩子函数都可以监听页面元素值的变化,在vue2中抛弃的过滤器filter函数因此被取代。
本文含有隐藏内容,请 开通VIP 后查看