您的位置:

用Vue实现页面加载动画效果

一、为什么需要页面加载动画效果

在网站或应用程序中,当用户进行页面跳转或点击某个链接时,由于网络延迟或资源加载等原因,页面加载的速度很慢,用户要长时间等待。这时,用户会感到焦虑、烦躁,甚至会选择离开页面。为了解决这个问题,需要在页面加载的过程中,添加动画效果,让用户有更好的体验感。

二、使用Vue实现页面加载动画效果的准备工作

在使用Vue实现页面加载动画效果之前,需要准备以下工作:

1. 安装Vue CLI:Vue CLI 是一个官方发布的用于快速开发Vue.js应用的系统;

    
        npm install -g vue-cli
    

2. 创建Vue项目:使用Vue CLI创建项目,使用webpack模板,这样可以快速地搭建Vue环境;

    
        vue init webpack my-project
    

3. 安装需要的依赖:本文中,我们将使用animate.css来实现动画效果,因此需要安装animate.css的相应依赖;

    
        npm install animate.css --save
    

三、使用Vue实现页面加载动画效果的实现步骤

在上述准备工作完成之后,我们可以按照以下步骤使用Vue实现页面加载动画效果:

步骤1、在App.vue文件中添加样式

在App.vue文件中,我们可以为加载动画效果添加相关的样式。这里,我们使用animate.css的fadeIn动画。代码如下:

    
        <template>
            <transition name="fade" mode="out-in">
                <router-view/>
            </transition>
        </template>

        <style>
            .fade-enter-active, .fade-leave-active {
                transition: opacity .5s;
            }
            .fade-enter, .fade-leave-to /* .fade-leave-active in below version 2.1.8 */ {
                opacity: 0;
            }
            .animated {
                animation-duration: .5s;
                animation-fill-mode: both;
            }
            .fadeIn {
                animation-name: fadeIn;
            }
            @keyframes fadeIn {
                0% {
                    opacity: 0;
                }
                100% {
                    opacity: 1;
                }
            }
        </style>
    

步骤2、在main.js中引入animate.css,并设置全局样式

在main.js文件中,我们可以引用animate.css,并设置全局样式,以支持我们在App.vue中使用的fadeIn动画。代码如下:

    
        import Vue from 'vue'
        import App from './App'
        import router from './router'
        import 'animate.css'

        Vue.config.productionTip = false

        /* eslint-disable no-new */
        new Vue({
            el: '#app',
            router,
            components: {
                App
            },
            template: '<App/>'
        })

        Vue.prototype.$animate = function (className, el, cb) {
            const animCls = 'animated ' + className;
            el.classList.add(animCls);

            function animEnd(e) {
                el.classList.remove(animCls);
                el.removeEventListener('animationend', animEnd);
                cb && cb(e);
            }

            el.addEventListener('animationend', animEnd);
        };
        Vue.mixin({
            mounted() {
                let el = this.$el;
                let cls = el.dataset.animate;
                if (cls) {
                    this.$animate(cls, el);
                }
            }
        });
    

步骤3、在router.js中添加全局的路由守卫

在router.js文件中,我们可以添加全局的路由守卫,以在切换路由时触发动画效果。代码如下:

    
        import Vue from 'vue'
        import Router from 'vue-router'
        import Home from '@/components/Home'
        import About from '@/components/About'

        const originalPush = Router.prototype.push;
        Router.prototype.push = function push(location) {
            return originalPush.call(this, location).catch(err => err);
        };

        Vue.use(Router)

        const router = new Router({
            routes: [{
                    path: '/',
                    name: 'Home',
                    component: Home
                },
                {
                    path: '/about',
                    name: 'About',
                    component: About
                }
            ]
        });

        const cssTransition = 'fade';

        router.beforeEach((to, from, next) => {
            if (to.path === from.path) {
                return false;
            }

            let toDepth = to.path.split('/').length;
            let fromDepth = from.path.split('/').length;
            let transitionName = cssTransition;

            if (toDepth < fromDepth) {
                transitionName = 'fade-back';
            }
            to.meta.transitionName = cssTransition;

            next();
        });

        export default router;
    

步骤4、使用组件切换路由,触发动画效果

现在,我们可以使用组件切换路由(如router-link),触发动画效果。代码如下:

    
        <template>
            <div class="app">
                <header>
                    <nav>
                        <router-link to="/" data-animate="fadeIn">Home</router-link>
                        <router-link to="/about" data-animate="fadeIn">About</router-link>
                    </nav>
                </header>

                <div class="main">
                    <transition name="fade" mode="out-in">
                        <router-view/>
                    </transition>
                </div>
            </div>
        </template>
    

总结:

使用Vue实现页面加载动画效果,需要遵循以上4个步骤。在App.vue中添加动画样式,在main.js中引入animate.css和设置全局样式,在router.js中添加全局路由守卫,在组件中添加data-animate属性来触发动画效果。这样就可以为用户提供更好的页面加载体验。

用Vue实现页面加载动画效果

2023-05-19
Vue实现动画效果展开与收起

2023-05-21
Vue动画效果详解

2023-05-19
Vue加载动画指南

2023-05-19
如何使用Vue实现数字滚动效果

2023-05-17
使用VueScrollTo实现网页平滑滚动效果

2023-05-16
vue页面加载完毕调用函数的实现方法

2023-05-19
使用video标签实现网页动画背景效果

2023-05-20
Vue页面加载优化:如何让页面更快加载?

2023-05-17
when-present<#else>when-missing. (These only cover the last step of the expression; to cover the whole expression, use parenthesis: (myOptionalVar.foo)!myDefault, (myOptionalVar.foo)?? ---- ---- FTL stack trace ("~" means nesting-related): - Failed at: ${item.id} [in template "article/detail/index.ftl" at line 48, column 106] ---- Java stack trace (for programmers): ---- freemarker.core.InvalidReferenceException: [... Exception message was already printed; see it above ...] at freemarker.core.InvalidReferenceException.getInstance(InvalidReferenceException.java:134) at freemarker.core.EvalUtil.coerceModelToTextualCommon(EvalUtil.java:481) at freemarker.core.EvalUtil.coerceModelToStringOrMarkup(EvalUtil.java:401) at freemarker.core.EvalUtil.coerceModelToStringOrMarkup(EvalUtil.java:370) at freemarker.core.DollarVariable.calculateInterpolatedStringOrMarkup(DollarVariable.java:104) at freemarker.core.DollarVariable.accept(DollarVariable.java:63) at freemarker.core.Environment.visit(Environment.java:371) at freemarker.core.IteratorBlock$IterationContext.executedNestedContentForCollOrSeqListing(IteratorBlock.java:321) at freemarker.core.IteratorBlock$IterationContext.executeNestedContent(IteratorBlock.java:271) at freemarker.core.IteratorBlock$IterationContext.accept(IteratorBlock.java:244) at freemarker.core.Environment.visitIteratorBlock(Environment.java:645) at freemarker.core.IteratorBlock.acceptWithResult(IteratorBlock.java:108) at freemarker.core.IteratorBlock.accept(IteratorBlock.java:94) at freemarker.core.Environment.visit(Environment.java:335) at freemarker.core.Environment.visit(Environment.java:341) at freemarker.core.Environment.visit(Environment.java:341) at freemarker.core.Environment.process(Environment.java:314) at freemarker.template.Template.process(Template.java:383) at org.springframework.web.servlet.view.freemarker.FreeMarkerView.processTemplate(FreeMarkerView.java:332) at org.springframework.web.servlet.view.freemarker.FreeMarkerView.doRender(FreeMarkerView.java:266) at org.springframework.web.servlet.view.freemarker.FreeMarkerView.renderMergedTemplateModel(FreeMarkerView.java:220) at org.springframework.web.servlet.view.AbstractTemplateView.renderMergedOutputModel(AbstractTemplateView.java:181) at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:314) at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1431) at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1167) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1106) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:979) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:903) at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:564) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885) at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:205) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at com.software.filter.HttpSpiderIdentifyFilter.doFilter(HttpSpiderIdentifyFilter.java:51) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:340) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:896) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1744) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52) at java.base/java.lang.VirtualThread.run(VirtualThread.java:309)