开发中常用的小技巧
1.简写技巧
1.1 声明变量
let x= 20;
let y= 20;
let x , y=20
let a= 1;
let b= 2;
let c= 3;
let [a,b,c]= [1,2,3]
1.2冒泡排序
let a= 5;
let b= 6;
let c;
c=a;
a=b;
b=c;
[a,b]=[b,a]
1.3向下取整Math.floor()简写
const floor=Math.floor(5.4)
const floor=~~5.4;
1.4寻找数组中的最大值和最小值,计算平均值
let arr= [1,3,5,7,9,15];
let max=Math.max(...arr);
let min =Math.min(...arr);
let average=arr.reduce((a,b)=>a+b/arr.length);
let max=arr.reduce((a,b)=>a>b?a:b);
let min=arr.reduce((a,b)=>a<b?a:b);
1.5扩展运算符(...)运用
let arr= [1,2];
let arr1= [3,4];
let newarr=arr.concat(...arr1);
arr.push(...arr1);
let newarr=[...arr,...arr1]
let a=[1,2,3];
let b= [1,2,,4,5];
let newarr=[...new Set(arr.concat(...arr1))]
let x={
name:"小花",
};
let y={
age:18
};
let obj={...x,...y}
let a="asdf";
let b=[...];
1.6翻转字符串
const res=str=>str.split('').reverse().join('')
res('holle wored')
1.7将对象转化成数组
const obj = { a: 1, b: 2, c: 3 };
let a= Object.entries(obj);
(3) [Array(2), Array(2), Array(2)]
0: (2) ["a", 1]
1: (2) ["b", 2]
2: (2) ["c", 3]
length: 3
let b= Object.keys(obj);
(3) ["a", "b", "c"]
let c= Object.values(obj);
(3) [1, 2, 3]
3.加快你开发的小技能
1.记住列表的滚动位置
function findScroller(element){
element.onscroll=function(){ console.log(element)}
Array.form(element.children).forEach(findScroller)
}
findScroller(document.body)
小提示:
如果在做移动端的主体部分滑动,为保证上一个页面的窗口位置固定为之前滑动的位置,可以
固定高:hight: 单位为:vh (窗口可视,);
溢出滚动:overflow-y:auto
2.模拟请求失败
if (Math.random() > 0.5) {
JSON.parse('alksdjak')
}
3.时间日期格式化(moment 、dayjs)
import Vue from 'vue'
import moment from 'moment'
Vue.filter('datedormat', (strData) => {
return moment(strData).format('YYYY-MM-DD hh:mm:ss')
})
import '@/filters/index.js'
{{ time| datadormat}}
4.移动端使用file时的注意事项
<!-- 选择文件 -->
<input
type="file"
hidden
ref="file"
@change="onfileChanege"
/>
onfileChanege() {
const file = this.$refs.file.files[0]
this.img = window.URL.createObjectURL(file)
this.isUserPhotoShow = true
this.$refs.file.value = ''
}
5.图片裁剪器
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
const image = this.$refs.img
const cropper = new Cropper(image, {
viewMode: 1,
dragMode: 'move',
aspectRatio: 1,
autoCropArea: 1,
cropBoxMovable: false,
cropBoxResizable: false,
background: false
})
console.log(cropper)
6 promise 对象(async /await)
如何声明一个promise
new promise(function(resolve,reject){
resolve('成功')
}).than(resolve=>{
alert(resolve)
})
new promise(function(resolve,reject){
reject('失败了')
}).catch(reject=>{
alert(reject)
})
如何终止在某个执行链的位置,可以用Promise.reject(new Error())
new promise(function(resolve,reject){
resolve(1)
}).than(result=>{
return result+1
}).than(result=>{
return result+1
}).than(result=>{
return result+1
}).than(result=>{
return Promise.reject(new Error(result+'失败'))
}).than(result=>{
return result+1
}).catch(error=>{
alert(error)
})
async /await
await 表示强制等待的意思,该关键字后面要跟一个promise对象,他总是等到该promise对象resolve成功之后执行,并且会返回resolve的结果
<button @click="text"></button>
methods:{
async text(){
const result= await new promise(function(resolve){
setTimeout(function(){
resolve(100)
},5000)
})
console.log(result)
}
}
捕获异常try/catch
6-2利用class 来封装一个promise
class myPromise {
static PENDING = 'pending'
static FULFILLED = 'fulfilled'
static REJECTED = "rejected"
constructor(fun) {
this.promiseState = myPromise.PENDING
this.promiseResult = null
return fun(this.resolve.bind(this), this.reject.bind(this))
}
resolve(res) {
if (this.promiseState === myPromise.PENDING) {
this.promiseState = myPromise.FULFILLED
}
return this.promiseResult = res
}
reject(rej) {
if (this.promiseState === myPromise.PENDING) {
this.promiseState = myPromise.REJECTED
}
return this.promiseResult = rej
}
}
const p = new myPromise(resolve => {
resolve('成功了')
})
console.log(p);
7 扁形转树状
const data =[
{ id: "01", label: "张三", pid: "" },
{ id: "02", label: "张四", pid: "01" },
{ id: "03", label: "张五", pid: "01" },
{ id: "04", label: "张六", pid: "02" },
{ id: "07", label: "张七", pid: "02" },
{ id: "08", label: "张八", pid: "02" },
]
function tree(list,rootValue){
const arr=[];
list.forEach(item=>{
if(item.pid===rootValue){
const children=tree(list,item.id)
item.children=children
arr.push(item)
}
})
return arr
}
tree(data,'')
8 解决跨域方式
- jsonp 优点:简单 缺点:get,前后端复杂
- 服务器代理 优点:适应强,后端不需要配合 缺点:搭建服务器
- cros 优点:前端不需要改代码 缺点:需要后端支持
9.vue脚手架代理服务器的运用
devServer:{
port:port,
open:true,
proxy:{
[process.env.VUE_APP_BASE_API]: {
target:'http://www.baiwu.com',
changeOrigin:true,
pathRewrite:{
'^/api':''
}
}
}
}
10.solt 的使用
- 当我们封装组件的时候 如果在子组件有点击事件啥的 可以利用solt将这些事件放到父组件上,就可以省略了组件之间的传信
4添加自己的配置片段
{
"vue文件结构": {
"prefix": "v2",
"body": [
"<template>",
" <div class=\"\"></div>",
"</template>",
"",
"<script>",
"export default {",
" name: '',",
" props: {},",
" data() {",
" return {}",
" },",
" created() {},",
" methods: {},",
" computed: {},",
" watch: {},",
" components: {}",
"}",
"</script>",
"",
"<style lang=\"less\" scoped>",
"</style>",
""
],
"description": "vue 三个标签结构 ,div容器,导入 lib/vue.js,创建vue 实例"
}
}