面试题答案
一键面试全局前置守卫
全局前置守卫会在每次路由切换前被调用,非常适合做权限控制。例如,只有登录用户才能访问某些页面。
import router from './router'
import store from './store'
router.beforeEach((to, from, next) => {
const isLoggedIn = store.getters.isLoggedIn
if (to.meta.requiresAuth &&!isLoggedIn) {
next('/login')
} else {
next()
}
})
在路由配置中,需要添加 meta
字段来标记需要登录才能访问的页面:
const routes = [
{
path: '/home',
name: 'Home',
component: Home,
meta: { requiresAuth: true }
},
{
path: '/login',
name: 'Login',
component: Login
}
]
路由独享守卫
路由独享守卫只对特定路由生效。比如,一个支付页面,只有在购物车有商品且用户已登录时才能访问。
const routes = [
{
path: '/payment',
name: 'Payment',
component: Payment,
beforeEnter: (to, from, next) => {
const isLoggedIn = store.getters.isLoggedIn
const hasItemsInCart = store.getters.hasItemsInCart
if (isLoggedIn && hasItemsInCart) {
next()
} else {
if (!isLoggedIn) {
next('/login')
} else {
next('/cart')
}
}
}
}
]
组件内守卫
组件内守卫在组件内部定义,可用于在进入或离开组件时执行逻辑。例如,在编辑页面离开时提示用户保存未保存的更改。
<template>
<div>
<input v-model="editedContent" />
</div>
</template>
<script>
export default {
data() {
return {
editedContent: ''
}
},
beforeRouteLeave(to, from, next) {
if (this.editedContent && window.confirm('你有未保存的更改,确定离开吗?')) {
next()
} else {
next(false)
}
}
}
</script>