我们可以注入到Vue3的路由中,从而依赖于Vue的事件触发来更贴近框架的原生体验
首先查看Vue路由的使用方法
import { createMemoryHistory, createRouter } from 'vue-router'
import HomeView from './HomeView.vue'
import AboutView from './AboutView.vue'
const routes = [
{ path: '/', component: HomeView },
{ path: '/about', component: AboutView },
]
const router = createRouter({
history: createMemoryHistory(),
routes,
})
createApp(App)
.use(router)
.mount('#app')
可以看到创建了router对象然后调用use使用,我们恰好可以通过use进行注入
// ==UserScript==
// @name Vue3路由注入测试
// @namespace https://bbs.tampermonkey.net.cn/
// @version 0.1.0
// @description try to take over the world!
// @author You
// @match http://localhost:5173/
// @grant unsafeWindow
// @run-at document-start
// ==/UserScript==
const originWeakSet = WeakSet;
unsafeWindow.WeakSet = function () {
const instance = new originWeakSet();
const has = instance.has
instance.has = function (...args) {
if (args[0].addRoute !== undefined) {
console.log('找到了路由',args[0])
const router=args[0]
router.afterEach((to,from,fail)=>{
console.log(to,from,fail)
})
}
return has.call(this, ...args)
}
return instance
}
这里我们挂了afterEach钩子进行测试,也可以使用beforeEach,beforeResolve等钩子
实测已经成功得到了路由实例并且进行操控
同理我们也可以利用use对pinia等插件进行劫持
// ==UserScript==
// @name Vue3路由注入测试
// @namespace https://bbs.tampermonkey.net.cn/
// @version 0.1.0
// @description try to take over the world!
// @author You
// @match http://localhost:5173/*
// @grant unsafeWindow
// @run-at document-start
// ==/UserScript==
const originWeakSet = WeakSet;
unsafeWindow.WeakSet = function () {
const instance = new originWeakSet();
const has = instance.has
instance.has = function (...args) {
debugger
if (args[0].state !== undefined) {
console.log('找到了pinia注册实例',args[0])
}
return has.call(this, ...args)
}
return instance
}
只需要找到找到关键的属性名进行判断即可
那么到这里你就了解了use注入以及路由和pinia的获取方式~
撒花~