本文最后更新于:2023年9月6日 晚上
需求说明
在一个中大型项目中,常常因为文件很多,不能立马找到需要修改的页面的源文件,所以就有了这个
作用:打印出当前页面的源文件地址
先看使用
默认使用
在App.vue中混入即可(默认console.log打印)
1 2 3 4 5 6 7 8 9 10 11 12 13
| <script> import { initMixinPrint } from "@/views/printFilePath";
export default { mixins: [initMixinPrint()] } </script>
<template> <div id="app"> <router-view /> </div> </template>
|


当printFilePath同目录下存在f-log.js,将自动使用f-log.js的个性化打印
f-log.js来源: 封装个性化console-log
当f-log.js未找到或出现其他错误,默认使用console.log
自定义处理
使用如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <script> import { initMixinPrint } from "@/views/printFilePath";
const printLog = (title, path) => { console.log(title, path) } export default { mixins: [initMixinPrint(printLog)] } </script>
<template> <div id="app"> <router-view /> </div> </template>
|
单纯的使用console.log,也可以简写或直接不指定(不指定的前提是printFilePath.js同目录下没有f-log.js)
1 2 3 4 5 6 7 8 9 10 11 12 13
| <script> import { initMixinPrint } from "@/views/printFilePath"; export default { mixins: [initMixinPrint(console.log)] } </script>
<template> <div id="app"> <router-view /> </div> </template>
|
手动打印
当然,当自己想要在适当的时机自己控制打印时,可以使用 printFilePath函数,只要传入当前实例(this)即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <script> import { printFilePath } from "@/views/printFilePath"; export default { mounted () { printFilePath(this, console.log) } } </script>
<template> <div id="app"> <router-view /> </div> </template>
|
printFilePath的第二个参数也是一个函数,不传递默认使用f-log.js
printFilePath.js
vue2 + vue-router3 版本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
let defaultPrintEvent try { defaultPrintEvent = await require('./f-log.js').initLog() } catch (e) { defaultPrintEvent = console.log }
const printFilePath = ({ $router } = {}, printEvent = defaultPrintEvent) => { if (process.env.NODE_ENV !== 'development' || !$router) return const matchedComponents = $router.getMatchedComponents() const lastIndex = matchedComponents.length - 1 matchedComponents.forEach(({ __file }, index) => { let tip = 'source' if (lastIndex === index) tip += '-deep' else tip += `-${index+1}` if (__file) printEvent(tip, __file) }) } const initMixinPrint = printEvent => ({ watch: { $router: { handler () { printFilePath(this, printEvent) }, immediate: true, } } }) export { initMixinPrint, printFilePath }
|
vue3 + vue-router4 版本(有时间补上)