文章以提示框Toast为例实现Vue全局插件封装,并在全局中使用。
main.js中引入
import ToastInfo from '@/plugin/toastInfo.js';
Vue.use(ToastInfo);
在单页面的使用
methods:{ open2() { this.$toastInfo({ message: '发布时间设置成功' }); }, }
toastInfo.vue
<template>
<div class="toast-info" v-if="show">
<p>{{message}}</p>
</div>
</template>
<script>
export default {
data() {
return {
message: '',
show: true,
handlerHide: null
};
},
mounted() {
this.hide();
},
methods: {
hide() {
setTimeout(() => {
this.show = false;
}, 2000);
},
cancelInfo() {
this.handlerHide && this.handlerHide();
}
}
};
</script>
<style lang="less" scoped>
.toast-info {
position: fixed;
top: 30px;
left: 50%;
width: 500px;
height: 60px;
line-height: 60px;
background-color: #262626;
text-align: center;
transform: translateX(-50%);
border: 1px solid #262626;
z-index: 9999;
color: #ffffff;
border-radius: 3px;
}
</style>
toastInfo.js
import Vue from 'vue'; import toastInfo from './toastInfo.vue'; const ToastInfo = (config) => { let options = { message: null, handlerHide: null }; if (config && typeof config !== 'object') { options.content = config; } config = { ...options, ...config }; let Tpl = Vue.extend(toastInfo); let instance = new Tpl(); for (let key in config) { if (config.hasOwnProperty(key)) instance.$data[key] = config[key]; } let toastList = document.querySelectorAll('.toast-info'); for (let i = 0; i < toastList.length; i++) { document.body.removeChild(toastList[i]); } document.body.appendChild(instance.$mount().$el); }; export default { install () { Vue.prototype.$toastInfo = ToastInfo.bind(Vue); } };
浙公网安备 33010602011771号