【发布时间】:2025-11-26 07:20:03
【问题描述】:
我是 Vue.js 的新手
我正在使用 Vue.js 2.4.4。 我在 app.js 文件中创建了全局 mixin:
...
import router from './router'
...(some imports and plugins definitions)
Vue.use(VeeValidate);
Vue.component(VuePassword);
...
Vue.mixin({
data: function(){
return {
get auth(){
return Auth;
}
}
}
});
const app = new Vue({
el: '#root',
template: `<app></app>`,
components: { App },
router
});
这个 mixin 导入一些带有验证方法的 Auth 对象 e.t.c 需要在每个组件中。 我所有的组件都可以检查这个 mixin 并且它工作正常。
但是我需要在每次路由请求后检查身份验证状态,并且我想使用我当前存在的 mixin,所以我试图在我的 router.js 文件中做这样的事情:
import Vue from 'vue'
import VueRouter from 'vue-router'
...
Vue.use(VueRouter);
const router = new VueRouter({
routes:[
...
]
});
router.beforeEach((to, from, next) => {
if(to.meta.requiresAuth) {
if(...call to mixin method) {
next();
} else {
next('/');
}
} else {
next();
}
});
export default router
问题: 有没有办法获取全局 mixin 对象并更改它的内部值,或者您能否提供一些小建议或示例什么是此类任务的正确解决方案? 还是应该使用插件而不是 mixins?
【问题讨论】:
-
Vuex的完美情况。它是 Vue 的状态机。您将所有身份验证信息保存在状态中,然后使用路由器和 mixin 读取它。 -
完美! :) 我会尝试你的建议。
标签: vue.js vuejs2 vue-router vue-mixin