如何在 Vue 中停止组件加载和重定向?
How to stop component-loading and redirect in Vue?
我有一个组件,非登录用户无法访问。我将此逻辑实现到 beforeCreate
挂钩中。问题是这不会阻止组件继续加载,这是我希望的。
这是我的代码:
<script>
export default {
beforeCreate: function () {
if (this.$root.auth.user === null) {
this.$router.push({ name: 'auth.login' })
}
},
mounted: function () {
// some code that SHOULD NOT be processed
// if the user isn't authenticated
}
}
</script>
我做错了什么?
您应该将 beforeCreate 函数移动到路由器本身。
这是我的 Auth catch
router.beforeEach(
(to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// if route requires auth and user isn't authenticated
if (!store.state.Authentication.authenticated) {
let query = to.fullPath.match(/^\/$/) ? {} : { redirect: to.fullPath }
next(
{
path: '/login',
query: query
}
)
return
}
}
next()
}
)
它允许我使用我的路由定义来处理身份验证和访客放置。
{
path: '/',
component: load('Template'),
children: [
{ path: '', component: load('Dashboard'), name: 'Dashboard' }
],
meta: { requiresAuth: true }
},
{
path: '/login',
component: load('Authentication/Login'),
name: 'login'
},
通过在 Vue 初始化组件之前在路由器中调用它,这将停止处理任何组件级别的事件。
我有一个组件,非登录用户无法访问。我将此逻辑实现到 beforeCreate
挂钩中。问题是这不会阻止组件继续加载,这是我希望的。
这是我的代码:
<script>
export default {
beforeCreate: function () {
if (this.$root.auth.user === null) {
this.$router.push({ name: 'auth.login' })
}
},
mounted: function () {
// some code that SHOULD NOT be processed
// if the user isn't authenticated
}
}
</script>
我做错了什么?
您应该将 beforeCreate 函数移动到路由器本身。 这是我的 Auth catch
router.beforeEach(
(to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// if route requires auth and user isn't authenticated
if (!store.state.Authentication.authenticated) {
let query = to.fullPath.match(/^\/$/) ? {} : { redirect: to.fullPath }
next(
{
path: '/login',
query: query
}
)
return
}
}
next()
}
)
它允许我使用我的路由定义来处理身份验证和访客放置。
{
path: '/',
component: load('Template'),
children: [
{ path: '', component: load('Dashboard'), name: 'Dashboard' }
],
meta: { requiresAuth: true }
},
{
path: '/login',
component: load('Authentication/Login'),
name: 'login'
},
通过在 Vue 初始化组件之前在路由器中调用它,这将停止处理任何组件级别的事件。