一、 当前路由切换
this.$router.replace({
path: this.$route.path,
query: {
...this.$route.query,
methods: 'check',
pageType: 'view'
}
})
二、页面多个表单校验
try {
await Promise.all([
this.$refs.preStepForm.validate(),
this.$refs.fileForm.validate(),
]);
} catch (error) {
return;
}
三、iframe传参
// iframe 传参给父级
window.parent.postMessage({ key: 'iframeBackState', newValue: '9' }, '*')
// 父级接受 iframe 传参
window.addEventListener('message', (ev) => {
if (ev.data.key === 'iframeBackState') {
// do some thing
}
})
四、获取当前PDF页码
$("#ccc")[0].contentDocument.getElementById('pageNumber').value // 获取当前PDF页码
this.$refs[projectInfoPdfIframe] && this.$refs[projectInfoPdfIframe][0] && this.$refs[projectInfoPdfIframe][0].contentWindow
&& this.$refs[projectInfoPdfIframe][0].contentWindow.renderPage
&& this.$refs[projectInfoPdfIframe][0].contentWindow.getPageNum()
五、input输入框对值的改变及限制
onkeyup="value=value.replace(/[^a-zA-Z0-9]/g,'')"
oninput="if(value.length>4)value=value.slice(0,4)"
// /(^[1-9]\d*$)/ --->纯数字输入
oninput="if(value.indexOf('.')>0 {value=value.slice(0,value.indexOf('.')+7)}" // 只能输入六位小数
<el-input :value="projInfo.id&&projInfo.id.replace('、',';')" ></el-input>
<el-input
:value="
baseForm.prices
? (baseForm.prices/ 100).toFixed(2)
: ''
"
placeholder="请输入"
>
<template slot="suffix">元</template>
</el-input>
// 两个数字之间生成随机数
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
console.log(random(1, 50));
// 日期之间的天数
const daysDiff = (date, date2) => Math.ceil(Math.abs(date - date2) / 86400000);
console.log(daysDiff(new Date('2021-05-10'), new Date('2021-11-25')));
// 检查代码是否在浏览器中运行
const isBrowser = typeof window === 'object' && typeof document === 'object';
// 对象数组求和
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
[{age:11}, {age:22}, {age:33}].reduce((total, p)=> total+p.age, 0)
并发执行Promise.all
// 并发执行
const responses = [];
for (const url of urls) {
const response = fetch(url);
responses.push(response);
}
await Promise.all(responses);
props、attrs使用
console.log(this.$attrs, 'nested组件的attr') // 获取父组件中未接收的属性传值
console.log(this.$props, 'nested组件的props') // 获取父组件中已接收的属性值
------------------------------------------------------
1、v-on="$listeners"
父组件A,子组件B,孙组件C。
C组件中emit事件后,在B中可以直接使用v-on="$listeners"接收,此时可以在A组件中的B上直接使用C中emit出来的事件。
2、v-bind="$attrs"
父组件A,子组件B,孙组件C。
A上设置值,若没在B上用props进行接收,则可以直接在B中的C设置v-bind="$attrs",此时相当于把属性直接设置在C上。
自定义指令
bind:只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。
inserted:被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)。
update:所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。
componentUpdated:指令所在组件的 VNode 及其子 VNode 全部更新后调用。
unbind:只调用一次,指令与元素解绑时调用。
// 防抖
const debounce = (fn, time) => {
let timeout = null;
return function() {
clearTimeout(timeout)
timeout = setTimeout(() => {
fn.apply(this, arguments);
}, time);
}
}
// 节流
const throttle = (fn, time) => {
let flag = true;
return function() {
if (!flag) return;
flag = false;
setTimeout(() => {
fn.apply(this, arguments);
flag = true;
}, time);
}
}
类型判断
typeof: 只能判断基本数据类型 typeof null // 'object'
instanceof: 实例 [] instanceof Array // true
construct
Object.prototype.toString.call() Object.prototype.toString.call(null) // '[object Null]'
方法(methods)里面调用filter方法
this.$options.filters['filterFn'](v)
$comfirm字符串换行或自定义
// confirm字符串拼接
async test() {
console.log(this.$parent, this.checkLowValueFn(), 999999)
debugger
// 将要显示的文件放在一个数组中
const confirmText = [
'你喜欢做一个存粹的技术人吗?',
'还挺喜欢的'
]
const newDatas = []
const h = this.$createElement
newDatas.push(h('h4', '库存不足,是否继续计费?'))
for (const i in confirmText) {
newDatas.push(h('p', (i == 0 ? '详情:' : '') + confirmText[i]))
}
const res = await this.$confirm('提示', {
title: '低值耗材库存不足提示',
message: h('div', null, newDatas),
closeOnClickModal: false,
showCancelButton: true,
confirmButtonText: '确定',
cancelButtonText: '取消'
}).catch(() => {})
console.log(1111222, res)
debugger
return res
// .then(async() => {
// })
// .catch(error => {
// console.log(error)
// })
},
监听事件写法
//如果监听的是匿名函数,则 window.removeEventListener清除不了监听
window.addEventListener('resize', ()=>{this.methodA()})
// 方法里面直接调用清除功能(优化写法)
window.addEventListener('pushState', this.bindCurrent)
this.$once('hook:beforeDestroy', () => {
window.removeEventListener('pushState', this.bindCurrent)
})
// 示例如下
getServeTimeSetTime() {
// 开启定时器,五分钟获取一次服务器时间
const timer1 = setInterval(this.handleGetServerTime, 5 * 60 * 1000) //
this.$once('hook:beforeDestroy', () => {
clearInterval(timer1)
timer1 = null
})
}
history路由模式
window.history.pushState(state, title, url)
computed中可获取的数据
// computed中可获取数据
haha({ $attrs, $route, $store, $listeners, $ref }) {
console.log('$attrs', $attrs)
console.log('$route', $route)
console.log('$store', $store)
return 123
},
http-server服务代理运行
// http-server服务代理,可用于前端打包后的dist文件下运行
// http-server是一个简单的零配置的命令行http服务器 --proxy 需要代理的后端服务器
http-server -p 8888 -o --proxy http://68.32.101.72:8179
// 参数说明
-p 端口号 (默认 8080)
-a IP 地址 (默认 0.0.0.0) 指定的地址必须是空闲的
-d 显示目录列表 (默认 'True')
-i 显示 autoIndex (默认 'True')
-e or --ext 如果没有提供默认的文件扩展名(默认 'html')
-s or --silent 禁止日志信息输出
--cors 启用 CORS via the Access-Control-Allow-Origin header
-o 在开始服务后打开浏览器
-c 为 cache-control max-age header 设置Cache time(秒) , e.g. -c10 for 10 seconds (defaults to '3600'). 禁用 caching, 则使用 -c-1.
-U 或 --utc 使用UTC time 格式化log消息
-P or --proxy Proxies all requests which can't be resolved locally to the given url. e.g.: -P http://someurl.com
-S or --ssl 启用 https
-C or --cert ssl cert 文件路径 (default: cert.pem)
-K or --key Path to ssl key file (default: key.pem).
-r or --robots Provide a /robots.txt (whose content defaults to 'User-agent: *\nDisallow: /')
-h or --help 打印以上列表并退出
Class关键字
// Class 关键字
ESlass 继承,constructor()和 super()关键字
super()方法用来调用父类的构造函数;
constructor 是原型对象上的一个属性,默认指向这个原型的构造函数;
promise外部调用
原理是promise需要resolve、reject或者抛出异常才会终止
// 外部控制promise
let waitf = null;
let tAsync = async function () {
console.log(`----->`)
await new Promise((resolve) => {
waitf = resolve
});
console.log(`<-----`)
};
tAsync();
waitf()
//输出
//----->
//<-----
// 参考链接 链接:https://juejin.cn/post/6844903985674108942
v-clickoutside
// v-clickoutside 点击外面则触发事件,直接引用elementUI中的方法,hideFn是回调方法
import Clickoutside from 'element-ui/src/utils/clickoutside'
v-clickoutside="hideFn"