一、从何处开始
在Vue.js中,router.beforeEach是我们能够执行在路由改变前的钩子函数。它能够用于验证用户登录,权限判断,页面刷新等等。这里我们将会从多个方面对router.beforeEach进行详细的阐述。
二、router.beforeEach刷新才触发
router.beforeEach只有在url进行跳转刷新时才会触发。这也就意味着如果是直接网页选项卡进行的跳转,是不会触发router.beforeEach的。这种情况下我们需要使用router-link或者history进行跳转。下面的示例代码可以帮助你理解这个问题:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/contact', component: Contact }
]
const router = new VueRouter({
routes
})
router.beforeEach((to, from, next) => {
console.log('router.beforeEach:', to, from)
next()
})
new Vue({
router,
el: '#app',
render: h => h(App)
})
在这种情况下,我们打开浏览器的控制台,在选择不同的报告进行跳转时,能够看到router.beforeEach的相应输出。
三、router.beforeEach()函数写在哪里
在Vue.js中,我们可以在router实例化之后的任意时刻添加一个全局的beforeEach路由钩子函数。我们可以在main.js文件中进行添加:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
{ path: '/', component: Home },
// ...其他路由配置
]
const router = new VueRouter({
routes
})
router.beforeEach((to, from, next) => {
// 在这里写你的逻辑代码
})
new Vue({
router
}).$mount('#app')
四、router.beforeEach不执行的原因
下面我们来看一下,为什么router.beforeEach函数可能会无效:
- 路由传参时,跳转时没有传递参数。
- router.beforeEach内部没有使用next函数,或者使用了多次next函数。
- 路由本身就没有进行跳转。
下面的示例代码可以帮助你进行进一步了解:
router.beforeEach((to, from, next) => {
if (to.path === '/home') {
// 在'/home'页面,我们不进行路由跳转
} else {
next()
}
})
五、router.beforeEach执行多次
如果你对router.beforeEach多次执行很困惑,那么这里的解释或许能够帮助你。
每个router-view组件都会将route信息作为他的prop进行传递,所以只要路由发生改变,所有的router-view都会重新执行一次。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/250818.html