目录结构:
# |-- public
# |-- src
# | -- | -- components
# | -- | -- |-- Toast
# | -- | -- | -- | -- Toast.js
# | -- | -- | -- | -- Toast.vue
# |-- App.vue
# |-- main.js
先写一个Toast组件 Toast.vue
<template>
<div class="Toast" :class="type" v-if="showToast">
{{ message }}
</div>
</template>
<script>
export default {};
</script>
<style scoped>
.Toast {
position: fixed;
left: 50%;
top: 50%;
background: rgba(0, 0, 0, 0.6);
padding: 10px 20px;
border-radius: 5px;
transform: translate(-50%, -50%);
animation: show-toast 0.2s;
color: #fff;
overflow: hidden;
display: flex;
align-items: center;
}
@keyframes show-toast {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.success {
color: #67c23a;
background: rgb(225, 243, 216);
}
.warning {
color: #e6a23c;
background: rgb(250, 236, 216);
}
.fail {
color: #f56c6c;
background: rgb(253, 226, 226);
}
</style>
Toast.js
import Vue from 'vue';
import Toast from './Toast.vue'//引入Toast组件
const ToastComponent = Vue.extend(Toast);//这样延伸出来的 可以如同new Vue({})一样玩
/**
* params: showToast Boolean 是否显示toast
* params: type String toast提示类型 共normal success,fail,warning
* params: message String toast消息
* params: duration Number toast显示时间
* */
function $Toast(message, duration = 3000, type = "normal", showToast = true) {
const ToastDom = new ToastComponent({
name: "Toast",
el: document.createElement("div"),//将Toast组件放在一个div容器里
data() {//这边创建了data 组件那边就不需要data了
return {
message: message,
type: type,
showToast: showToast
}
}
})
document.body.appendChild(ToastDom.$el);//使用原生方法插入到body中
setTimeout(() => {
ToastDom.showToast = false;//显示几秒后消失
}, duration);
}
function initToast() {
//挂在到this上全局可使用
Vue.prototype.$Toast = $Toast
}
export default initToast;
main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
import Toast from './components/Toast/Toast.js';//引入就Toast.js
Vue.use(Toast);
new Vue({
render: h => h(App),
}).$mount('#app')
项目中使用:
this.$Toast("成功弹出✔", 3000,"success");
源码下载 :
评论