实时获取当前页面源文件地址

本文最后更新于: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>

image.png
image.png

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
/**
* @author Xin-FAS
*/

// 当前目录下不存在f-log.js同时不指定处理函数时,使用console.log
let defaultPrintEvent
try {
defaultPrintEvent = await require('./f-log.js').initLog()
} catch (e) {
defaultPrintEvent = console.log
}
/**
* 输出当前渲染页面的真实文件地址,和最深级的子路由地址(deep)
* @param that 当前实例对象,也就是this
* @param printEvent 指定回调,可以接受地址自己处理
*/
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 版本(有时间补上)


实时获取当前页面源文件地址
https://xin-fas.github.io/2023/08/28/实时获取当前页面源文件地址/
作者
Xin-FAS
发布于
2023年8月28日
更新于
2023年9月6日
许可协议