寫一個Vue loading 外掛
阿新 • • 發佈:2020-11-11
作者:imgss
出處:http://www.cnblogs.com/imgss
什麼是vue外掛?
- 從功能上說,外掛是為Vue新增全域性功能的一種機制,比如給Vue新增一個全域性元件,全域性指令等;
- 從程式碼結構上說,外掛就是一個必須擁有install方法的物件,這個方法的接收的第一個引數是Vue建構函式,還可以接收一個可選的引數,用於配置外掛:
var myplugin = { install:function(Vue,options){ ... } }
從意義上來說,正如jQuery的$.fn
使jQuery有了一個龐大的生態一樣,Vue的外掛機制使Vue形成了一個生態系統,你可以開發一個外掛給別人複用。
使用外掛
使用一個外掛,只要像下面這樣:
Vue.use(myPlugin)
寫一個loading外掛
光說不練假把式,接下來寫一個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="http://cdn.bootcss.com/vue/2.4.2/vue.js"></script> <script src="./loading.js"></script> <script> Vue.use(myPlugin); var app = new Vue({ el: '#app',data: { } }); </script> </body> </html>
這時基本上可以看到一個靜態效果。
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 ? duration + "s" : duration,animationDelay: parseInt(duration)/text.length*index +"s" }' v-for='char,index in text'> {{char}} </span>
到這裡,外掛基本完成,看一下效果:
demo
程式碼
codepen
以上就是寫一個Vue loading 外掛的詳細內容,更多關於Vue 外掛的資料請關注我們其它相關文章!