调用方式: this.$toast.show("成功");
components/toast/Toast.vue
<template>
<div class="toast" v-if="isShow">{{message}}
</div>
</template>
<script type="text/javascript">
export default {
name: "Toast",
data() {
return {
message:'',
isShow:false
}
},
methods:{
show(message, duration = 500){
this.isShow = true;
this.message = message;
setTimeout(()=>{
this.isShow = false;
this.message = '';
},duration)
}
}
}
</script>
<style scoped>
.toast {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 8px 10px;
z-index: 999;
color: #fff;
background-color: rgba(0, 0, 0, .75);
}
</style>
components/toast/index.js
import Toast from './Toast'
const obj = {}
obj.install = function(Vue){
//1.创建组件构造器
const toastContrustor = Vue.extend(Toast);
//2.new 的方式,根据组件构造器,可以创建出来一个组件对象
const toast = new toastContrustor();
//3.将组件对象,手动挂载到某一个元素上
toast.$mount(document.createElement('div'));
//4.toast.$el对应的就是 div
document.body.appendChild(toast.$el);
Vue.prototype.$toast = toast;
}
export default obj
main.js
import toast from './components/toast'
//安装 toast 插件
Vue.use(toast);