如何写一个Vue插件

Vue.js 的插件应当有一个公开方法 install 。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象:

MyPlugin.install = function (Vue, options) {
  // 1. 添加全局方法或属性
  Vue.myGlobalMethod = function () {
    // 逻辑...
  }

  // 2. 添加全局资源
  Vue.directive('my-directive', {
    bind (el, binding, vnode, oldVnode) {
      // 逻辑...
    }
    ...
  })

  // 3. 注入组件
  Vue.mixin({
    created: function () {
      // 逻辑...
    }
    ...
  })

  // 4. 添加实例方法
  Vue.prototype.$myMethod = function (methodOptions) {
    // 逻辑...
  }
}

其实这里就是将我们平时写的全局方法、属性等,写在一起通过install公开。

以下是自己写的一个简单的toast插件:

myToast.vue文件

< template >
< transition name= "fade" >
< div class= "toast" v-show=" showToast" >
< div class= "content" :class=" position| check" >
{{ text}}
</ div >
</ div >
</ transition >
</ template >

< script >
export default {
data() {
return {
showToast: false,
text: '',
position: 'center'
};
},
methods: {
show( text, position = 'center') {
this. showToast = true;
this. text = text;
this. position = position;
const that = this;
setTimeout(() => {
that. showToast = false;
}, 1000);
}
},
filters: {
check( val) {
return { [val]: true};
}
}
};
</ script >

< style lang= "scss" >
.fade-enter-active, .fade-leave-active {
transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
.toast{
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
z-index: 999999;
.content{
position: absolute;
left: 50%;
transform: translate( -50%, -50%);
background: rgba( 0, 0, 0, .6);
border-radius: 5px;
width: 80px;
text-align: center;
color: #fff;
font-size: 14px;
font-weight: 700;
line-height: 40px;
}
.top{
top: 10%;
}
.center{
top: 50%;
}
.bottom{
top: 90%;
}
}
</ style >



toast.js文件:

import toast from '../components/myToast';

export default {
install( Vue) {
const MyToast = Vue. extend( toast); //生成Vue的子元素
const instance = new MyToast();
instance. $mount( document. createElement( 'div'));
document. body. appendChild( instance. $el);
const { show} = instance;
Vue. prototype. $toast = {
show
};
}
};


这个时候只需将toast.js 引入到main.js文件中使用就可以了。

import Toast from './plugins/Toast';

Vue. use( Toast);


接下来就是如何使用了:

< p @click=" $toast. show( '复制完毕', 'top')" >toast-top </ p > //第一个参数是弹出的内容,第二个参数是toast的位置 'top','center','bottom'
< p @click=" $toast. show( '复制完毕', 'bottom')" >toast-bottom </ p >
< p @click=" $toast. show( '复制完毕')" >toast-center </ p >


好了,你可以试试了

猜你喜欢

转载自blog.csdn.net/lhb215215/article/details/80538094