经过添加实例方法,手写插件css
vue插件的编写方法分为4类,此篇文章经过添加实例方法编写插件vue
export default {
install(Vue, options){
Vue.prototype.$myMethods = function (options){
// 代码逻辑 添加实例方法,经过把它们添加到 Vue.prototype 上实现
}
}
}
复制代码
插件封装成组件app
若是咱们在组件的基础上编写插件,咱们能够使用Vue.extend(component)来进行,ide
loading插件实例flex
loading.vue组件
<template>
<div class="loadings" v-show="isShow">
<div class="c-loading">
<div class="c-l-loading"></div><span>{{text}}</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
}
},
props: {
isShow: Boolean,
text: {
type: String,
default:'正在加载中...'
}
}
}
</script>
<style lang="scss" rel="stylesheet/style" scope>
.loadings {
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
background: rgba(0,0,0,0.6);
display: flex;
align-items: center;
justify-content: center;
color: #fff;
z-index: 10000;
@keyframes mymove
{
from {width:0px;}
to {width:300px;}
}
.c-loading{
width:300px;
height:5px;
border-radius: 10px;
position: relative;
background:#f3f3f3;
span{
float: right;
margin-right: -60px;
margin-top: -10px;
}
}
.c-l-loading{
width:0px;
height:5px;
border-radius: 5px;
background:#409EFF;
animation:mymove 10s ease;
animation-fill-mode:forwards;
}
}
</style>
复制代码
封装该组件this
loading.js
import loading from './loading.vue'
let $vm = null
export default{
install(Vue, options){
if(!$vm){
let myLoading = Vue.extend(loading) //经过Vue.extend()方法建立了一个构造器
$vm = new myLoading({
el: document.createElement('div')
}) //经过构造器建立$vm实例,并挂载在div上
document.body.appendChild($vm.$el) //插入到Dom节点上
}
$vm.isShow = false //建立一个属性来控制显隐
let myMethods = {
show(text) {
$vm.isShow = true
$vm.text = text
},
hide() {
$vm.isShow = false
}
}
if(!Vue.$vLoading){
Vue.$vLoading = myMethods
Vue.prototype.$vLoading = Vue.$vLoading //添加实例方法
}else{
console.log('$vLoading方法已被占用')
}
}
}
复制代码
插件写完以后,在main.js中全局注册一下该插件,经过Vue.use()便可使用该插件,其会自动调用install方法,Vue.use会自动阻止屡次注册插件。spa
import Vue from 'vue'
import MyLoading from './loading.js'
Vue.use(MyLoading)
全局注册完成以后,咱们能够在页面中使用 this.$vLoadingshow() 来显示,使用 this.$vLoading.hide()来隐藏。
复制代码