使用vue自定义指令,简单实现骨架屏

599 阅读1分钟

骨架屏已经是一个老生常谈的话题了, 网上的实现方式也有很多,以前饿了么团队有个挺好用的插件但是现在烂尾了。正好最近团队将项目升级到vue3,趁这个机会通过vue的自定义指令顺便简单实现了下。

/** * 骨架屏 */
import { Directive } from "vue";
const skeleton: Directive = {
    mounted(el) {
        const { children } = el;
        children.forEach(element => {
            element.preBg = element.style.backgroundColor;
            if (element.offsetWidth > 1 && element.offsetHeight > 1) {
                element.style.backgroundColor = "#eee";
            } else {
                element.style.backgroundColor = "transparent";
            }            element.children.forEach(item => {
                item.preDisplay = item.style.display;
                item.style.display = "none";
            });
        });
    },
    beforeUpdate(el) {
        const { children } = el;
        children.forEach(element => {
            element.style.backgroundColor = element.preBg;
            element.children.forEach(item => {
                item.style.display = item.preDisplay;
            });
        });
    }};
export default skeleton;


// main.ts
 createApp(App)
        .use(store)
        .use(router)
        .directive("skeleton", skeleton)
        .mount("#app");

以上只是基本实现,满足一些简单的情况,如果大家有更好的想法或者改进,欢迎指正批评。