网络编程 
首页 > 网络编程 > 浏览文章

写一个Vue loading 插件

(编辑:jimmy 日期: 2024/5/8 浏览:3 次 )

作者:imgss

出处:http://www.cnblogs.com/imgss

什么是vue插件"htmlcode">

var myplugin = {
  install:function(Vue, options){
 ...
  }
}

从意义上来说,正如jQuery的$.fn使jQuery有了一个庞大的生态一样,Vue的插件机制使Vue形成了一个生态系统,你可以开发一个插件给别人复用。

使用插件

使用一个插件,只要像下面这样:

 Vue.use(myPlugin)

写一个loading插件

光说不练假把式,接下来写一个loading插件练练手,这个插件被封装成一个全局组件,实现下面的效果:

写一个Vue loading 插件

1 定义接口

我们希望应用这个插件的方式如下:

<loading text='imgss' duration='3'></loading>

其中,text用于定义loading动画显示的文字,duration定义动画时间

2 实现静态组件

新建一个loading.js文件:

 let myPlugin = {
 install: function (Vue, options) {
  Vue.component('loading', {
   props: {
    text:{
     type:String
    },
    duration:{
     type:String,
     default:'1s'//默认1s
    }
   },
   data: function() {
    return {};
   },
   template: `
    <div class='wrapper'>
     <div class='loading'>
      <span style='width:20px' v-for='char in text'>{{char}}</span>
     </div>
    </div>
   `
  });

这里模板的作用在于,将输入的字符串转换成组成字符串的字符构成的span元素;
接下来,新建一个html文件:

 <html>
 <head>
  <meta charset='utf-8'>
  <title>插件</title>
 </head>
 <body>
  <div id="app">
   <loading text='imgss'></loading>
   <loading text='我是一个粉刷匠' duration='2s'></loading>
  </div>
  <script src="/UploadFiles/2021-04-02/vue.js">

这时基本上可以看到一个静态效果。

3 加动画

给每个元素加上一个控制上下的animation

 @keyframes move {
  0% {
   margin-top: -10px;
   border-bottom: 1px solid;
  }
  50% {
   margin-top: 10px;
   border-bottom: none;
  }
  100% {
   margin-top: -10px;
  }
 }

除此之外,还有一下其他的公有样式代码,利用mounted生命周期函数,动态生成一个style标签,将css代码插到文档中:

   mounted: function () {
    var cssFlag = false;
    return function () {
     if (cssFlag) {
      return;
     }
     var head = document.querySelector('head');
     var style = document.createElement('style');
     style.type = 'text/css';
     style.innerText = `
     .wrapper{
      display: flex;
      justify-content: center;
     }
     .loading {
      display: flex;
      text-align: center;
      padding-top: 30px;
      height: 50px;
      justify-content: space-between;
     }
     .loading span {
      margin-top: 0;
      animation: ease infinite move;
      display: block;
     }

     @keyframes move {
      0% {
       margin-top: -10px;
       border-bottom: 1px solid;
      }
      50% {
       margin-top: 10px;
       border-bottom: none;
      }
      100% {
       margin-top: -10px;
      }
     }`;
     head.appendChild(style);
     cssFlag = true;
    };
   }(),

然后通过控制span的animation-delay来模拟曲线:

<span 
  :style='{
   width: "20px", 
   animationDuration: duration.indexOf("s") === -1 "s" : duration , 
   animationDelay: parseInt(duration)/text.length*index +"s"
  }' 
  v-for='char,index in text'>
  {{char}}
 </span>

到这里,插件基本完成,看一下效果:

写一个Vue loading 插件

demo

代码

codepen

以上就是写一个Vue loading 插件的详细内容,更多关于Vue 插件的资料请关注其它相关文章!

上一篇:vue实现标签云效果的示例
下一篇:解决Vue大括号字符换行踩的坑