Vue.js page transition fade effect with vue-router

前端 未结 2 605
耶瑟儿~
耶瑟儿~ 2021-01-30 03:23

How to achieve a fade effect page transition between vue-router defined pages (components)?

2条回答
  •  时光取名叫无心
    2021-01-30 03:41

    Wrap with and add these styles:

    .fade-enter-active, .fade-leave-active {
      transition-property: opacity;
      transition-duration: .25s;
    }
    
    .fade-enter-active {
      transition-delay: .25s;
    }
    
    .fade-enter, .fade-leave-active {
      opacity: 0
    }
    

    Detailed answer

    Assuming you have created your application with vue-cli, e.g.:

    vue init webpack fadetransition
    cd fadetransition
    npm install
    

    Install the router:

    npm i vue-router
    

    If you are not developing your app using vue-cli, make sure to add the vue router the standard way:

    
    
    

    You can use e.g.: https://unpkg.com/vue-router/dist/vue-router.js

    The CLI has created a backbone application for you, which you can add components to.

    1) Create page components

    In Vue, components (UI elements) can be nested. A page in your app can be made with a regular Vue component that is considered as the root to other components in that page.

    Go to src/ and create pages/ directory. These page-root components (individual pages) will be put in this directory, while the other components used in the actual pages can be put to the ready-made components/ directory.

    Create two pages in files called src/pages/Page1.vue and src/pages/Page2.vue for starters. Their content will be (edit page numbers respectively):

    
    
    
    
    
    

    2) Setup routing

    Edit the generated src/main.js add the required imports:

    import VueRouter from 'vue-router'
    import Page1 from './pages/Page1'
    import Page2 from './pages/Page2'
    

    Add a global router usage:

    Vue.use(VueRouter)
    

    Add a router setup:

    const router = new VueRouter({
      routes: [
        { path: '/page1', component: Page1 },
        { path: '/page2', component: Page2 },
        { path: '/', redirect: '/page1' }
      ]
    })
    

    The last route just redirects the initial path / to /page1. Edit the app initiation:

    new Vue({
      router,
      el: '#app',
      render: h => h(App)
    })
    

    The whole src/main.js example is at the end of the answer.

    3) Add a router view

    Routing is set up by now, just a place where the page components will be rendered according to the router is missing. This is done by placing somewhere in the templates, you will want to put it in the src/App.vue's