Vue组件loading加载效果实现

摘要

对于页面加载,网络请求等待,为了增强用户体验,往往会出现一个loading加载效果,相对减少用的焦虑感,那怎样去实现这样一个组件呢,可以用css的帧动画,也可以使用canvas画出这样一个动图。

本文将以css帧动画的形式实现loading加载效果
涉及的图片形式如下


image.png

1.采用css动画完成,keyframes定义0-100%的动画区间,每一个百分比运行的距离,一步完成所有的帧,无限循环,这种太过于冗余,得不偿失,不建议使用

// loading组件





2.也是采用css动画,图片有36张,就相当于是36帧,但是注意动画是从0开始的,实际看到第36张图的其实点是35的结尾,所以steps(35),keyframes定义100%的即可






3.其次就是封装成可以在任何地方调用的组件

/**
 * 使用方法
 * 显示loading 不是在实例化的组件中 Vue.showLoading()  如果是在vue的组件中使用则 this.$showLoading()
 * 关闭loading 不是在实例化的组件中 Vue.closeLoading()        如果是在vue的组件中使用则 this.$closeLoading()
 */

import ModalLoading from './ModalLoading.vue';
let ModalLoad = {};
ModalLoad.install = function(Vue) {
    // 在全局状态下只有一个实例 options = {}option = {}
    let instance;
    let defaultOptions = {
        needBg: false // 默认不需要背景
    };
    // 在Vue的原型上扩展方法
    Vue.showLoading = Vue.prototype.$showLoading = function(option) {
        defaultOptions = Object.assign(defaultOptions, option);
        // 实例化所引入的插件
        const ModalLoadController = Vue.extend(ModalLoading);
        // 判断当前实例是不是已经存在
        if (!instance) {
            // 实例化插件并挂在到某一个元素上
            instance = new ModalLoadController({
                el: document.createElement('div')
            });
            // 添加在body内
            document.body.appendChild(instance.$el);
        }
        if (instance.show) return;
        instance.show = true;
        instance.needBg = defaultOptions.needBg;
    };
    Vue.closeLoading = Vue.prototype.$closeLoading = function() {
        instance ? (instance.show = false) : '';
    };
};
// 自动安装插件
if (typeof window != 'undefined' && window.Vue) {
    // eslint-disable-next-line no-undef
    Vue.use(ModalLoad);
}
// 导出对象
export default ModalLoad;

4.使用方式

// 引入
import ModalLoading from "./components/index";
Vue.use(ModalLoading);

// 使用
Vue.showLoading();

5.效果

loading.gif

关于css animation中的animation-timing-function的取值,比如文中提及的steps()函数,可以参考MDN web docs

你可能感兴趣的:(Vue组件loading加载效果实现)