目录结构:
prompt
index.js
Prompt.vue
先封装组件 Prompt.vue
<template>
<div class="box" v-if="isShow">
<div class="flex">
{{ message }}
</div>
</div>
</template>
<script>
export default {
name: "Prompt",
data() {
return {
message: "默认提示",
isShow: false,
time: null,
};
},
methods: {
// 显示提示信息
show(message, duration = 1500) {
if (this.time) clearTimeout(this.time);
this.isShow = true;
this.message = message;
this.time = setTimeout(() => {
this.isShow = false;
this.message = "";
this.time = null;
}, duration);
},
},
};
</script>
<style scoped>
.box {
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
z-index: 9;
height: 25px;
background-color: rgb(97, 97, 97);
color: #fff;
border-radius: 3px;
font-size: 16px;
padding: 20px;
}
.flex {
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
</style>
index.js(自定义插件)
import Prompt from './Prompt'
const obj = {}
obj.install = function (Vue) {
// 创建组件构造器
const promptconstructor = Vue.extend(Prompt)
// new的方式 根据组件构造器可以创建一个组件对象
const prompt = new promptconstructor()
// 根据组件对象 手动挂载到某个DOM元素上
prompt.$mount(document.createElement('div'))
document.body.appendChild(prompt.$el)
// 添加实例方法
Vue.prototype.$prompt = prompt
}
export default obj
全局注册插件app.vue
// 自定义的组件(插件)
import prompt from 'components/common/prompt'
// 注册自定义组件(插件)
Vue.use(prompt)
调用
this.$prompt.show('提示信息');