Changing body styles in vue router

前端 未结 7 1420
滥情空心
滥情空心 2021-02-01 18:27

I\'m using Vue router with two pages:

let routes = [
    {
        path: \'/\',
        component: require(\'./components/HomeView.vue\')
    },
    {
        pa         


        
相关标签:
7条回答
  • 2021-02-01 19:33

    I ran into an issue when I wanted to modify the styles of the html and body tags along with the #app container on specific routes and what I found out is that for various reasons, this can be quite complicated.

    After reading through:

    • @Saurabh's answer on another relative question: https://stackoverflow.com/a/42336509/2110294
    • @Mteuahasan's comment above regarding Evan You's suggestion
    • @GluePear's / OP's answer to this question: https://stackoverflow.com/a/44544595/2110294
    • Sass style inclusion headaches: https://github.com/vuejs/vue-loader/issues/110#issuecomment-167376086

    In your App.vue (could be considered as the centralised state):

    <template>
      <div id="app">
        <router-view></router-view>
      </div>
    </template>
    
    <script>
      export default {
        name: 'my-app',
        methods: {
          handleStyles () {
            // Red style to the body tag for the home page
            if (['/'].includes(this.$route.path)) document.body.className = 'bg-red'
            // Pink style to the body tag for all other pages
            else if (document.body.classList.contains('bg-red')) document.body.className = 'bg-pink'
          }
        },
        // Handle styles when the app is initially loaded
        mounted () {
          this.handleStyles()
        },
        // Handle styles when the route changes
        watch: {
          '$route' () {
            this.handleStyles()
          }
        }
      }
    </script>
    
    <style>
      .bg-red {
        background: red;
      }
      .bg-pink {
        background: pink;
      }
    </style>
    

    So for the route / you get the red style and for all other routes the pink style is applied.

    The handleStyles logic could have been dealt with by the beforeCreated hook however in my case, this would only affect the html and body styles but the #app element where the router view is rendered into would only available when the dom has been mounted so I think that it is a slightly more extensible solution.

    0 讨论(0)
提交回复
热议问题