我是 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 对象,这些方法需要存在于每个组件中。 我的所有组件都可以检查这个 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?
最佳答案
我宁愿创建一个单独的文件进行身份验证,而不是使其成为混合文件。然后使用 Vue.use() 来在 vue 对象上设置身份验证。 文件的示例:
auth.js
export default function(Vue) {
Vue.auth = {
// do your auth logic
}
}
然后在你的主js文件中 main.js
import Auth from './auth.js'
Vue.use(Auth);
那么你应该可以使用Vue.auth 另一种选择是继续使用 mixin 并将值传递给商店(如 vuex),或者如果您的项目很小,则创建您自己的...
关于Vue.js/Mixins - 有没有办法在 vue 组件之外获取全局 mixin 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47307842/