如何在Vue导航守卫中访问Vue应用的methods方法?
Vue2导航守卫中访问根实例methods方法的可行方案
问题描述
我按照Vue2的指引在main.js的根Vue实例中添加了方法:
new Vue({ router, data: {}, methods: {aMethod: ()=> {}}, render: h => h(App), }).$mount('#app');
之后尝试在导航守卫中通过router.app.aMethod()访问该方法,却报错:
router.app.aMethod is not a function
使用的依赖版本:
... "dependencies": { ... "vue": "^2.6.14", "vue-router": "^2.7.0" },
原因分析与解决方案
1. 修复methods中的箭头函数问题
Vue的methods中禁止使用箭头函数——箭头函数没有独立的this,会绑定父级作用域的上下文,导致方法无法挂载到Vue实例上。需将箭头函数改为普通函数:
new Vue({ router, data: {}, methods: { aMethod() { // 改为普通函数 // 方法逻辑 } }, render: h => h(App), }).$mount('#app');
修改后,router.app.aMethod()即可正常调用。
2. 其他可选复用方案
如果需要在多处复用该方法,推荐以下两种方式:
- 挂载到Vue原型:在
main.js中将方法挂载到Vue原型,实现全局可访问Vue.prototype.$aMethod = function() { // 方法逻辑 } // 导航守卫中调用 router.beforeEach(async function (to, from, next) { router.app.$aMethod(); // 组件内可直接通过this.$aMethod()调用 }); - 抽离为独立工具函数:将方法单独放在工具文件中,按需导入使用
// utils/functions.js export function aMethod() { // 方法逻辑 } // 导航守卫中导入调用 import { aMethod } from '@/utils/functions.js' router.beforeEach(async function (to, from, next) { aMethod(); });
内容的提问来源于stack exchange,提问作者Jeff Tian
相关产品推荐
相关产品推荐

