文章目录
一、如何实现路由重新加载?
1-1、设置要刷新的组件v-if,通过v-if实现页面组件层重载。
<template>
<el-container>
<el-header>Header</el-header>
<el-container>
<el-aside width="200px">Aside</el-aside>
<el-main v-if="isRouterCache"> <router-view /></el-main>
</el-container>
</el-container>
</template>
<script>
export default {
name:'Layout',
data () {
return {
isRouterCache: true
}
},
methods: {
reload () {
this.isRouterCache = false
this.$nextTick(() => (this.isRouterCache = true))
}
}
}
</script>
注意:当前组件其实是layout.vue组件他的上一层还有app.vue组件。
1-2、对外暴露main.js中的 new Vue()实例。

1-3、来到我们的路由守卫配置页面。

1-4、配置router.beforeEach钩子守卫。
router.beforeEach((to, from, next) => {
// 此处用于判断 然后刷新main组件$vue.$root.$children[0].$children[0]就相当于与layout组件 对应可以获取到reload方法,从而实现刷新。
if ($vue.$root.$children[0].$children[0]) {
$vue.$root.$children[0].$children[0].reload()
}
next()
}
})
此处我们可以通过$vue去获取到当前组件的实例,再次通过$root去拿到我们的根组件,第一次 $children[0] 相当于app.vue,再一次相当于layout.vue组件,我们就可以通过这个组件实例去调用里面methods的方法。
这样既我们每次变更路由时,对应的main显示组件就会重载,这样也不会影响到如左侧或者上方的侧边栏、顶部栏等等。

本文介绍了在Vue.js应用中如何实现路由页面的重新加载,主要通过在组件中使用v-if来控制组件的重新加载,并结合路由守卫beforeEach进行配置。在layout.vue组件中设置v-if属性,根据条件决定是否重载页面。同时,在main.js中暴露Vue实例,并在路由守卫中调用组件的reload方法来刷新页面,确保在路由变化时只重载指定的组件,而不影响其他部分。

7952

被折叠的 条评论
为什么被折叠?



