如何利用Vue編寫一個 loading 插件?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
什么是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>到這里,插件基本完成,看一下效果:

關于如何利用Vue編寫一個 loading 插件問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。