foreword
Received a task at work recently:
light
There aredark
two theme colors in the project- a, b page defaults to
dark
- Other pages default to
light
Project front-end environment:
vue2+js+yarn+vuex+vuetify+element ui
Solutions
-
routerjs
Default theme settings when configuring paths in -
When clicking on the menu on the left
aside
, switch themes
The problem with idea 1: But vuetify
if it is mounted in vue
, routerjs
it may not be available in .
Hidden dangers in idea 2: When the route jumps from other pages, it cannot be detected, such as directly changing the navigation address
After many attempts, the problem of idea 1 has been solved, see below for specific usage
Instructions
isDark
1. Set attributes in routes a and b , as follows
{
path: '/posture',
name: 'a',
component: () => import('@/views/dashboards/posture/Posture.vue'),
meta: {
layout: 'content',
isDark: true,
},
},
2. router.afterEach()
Set the default theme color in
router.afterEach(to => {
console.log('router', router)
// router.app---vue实例
router.app.$vuetify.theme.dark = !!to.meta.isDark
})
Console output:
Other ways to get vue instances in vue-router
You can directly define the following routing navigation guards in the routing component, but it is convenient to use for individual routing jump operations. If it is a global transformation such as [default theme], using this will need to be defined once in each page, the code is redundant and It is complex and not recommended for global modification, but you can learn how to use it and the principle
Component routing navigation guards use
Console printout:
This is an example from the official website:
const Foo = {
template: `...`,
beforeRouteEnter(to, from, next) {
// 在渲染该组件的对应路由被 confirm 前调用
// 不!能!获取组件实例 `this`
// 因为当守卫执行前,组件实例还没被创建
},
beforeRouteUpdate(to, from, next) {
// 在当前路由改变,但是该组件被复用时调用
// 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
// 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
// 可以访问组件实例 `this`
},
beforeRouteLeave(to, from, next) {
// 导航离开该组件的对应路由时调用
// 可以访问组件实例 `this`
}
}
Navigation analysis process
- Navigation is triggered.
- Call guards in deactivated components
beforeRouteLeave
. - Call the global
beforeEach
guard. beforeRouteUpdate
Call guards (2.2+) in reusable components .- Called in routing configuration
beforeEnter
. - Parse asynchronous routing components.
- Called in the activated component
beforeRouteEnter
. - Calls the global
beforeResolve
guard (2.5+). - Navigation is confirmed.
- Call the global
afterEach
hook. - Triggers a DOM update.
- Call the callback function
beforeRouteEnter
passed in the guardnext
, and the created component instance will be passed in as the parameter of the callback function.