两种全局组件引入
main.js
import toastRegistry from './components/toast/index'
import empty from './components/empty/empty'
Vue.use(toastRegistry)
Vue.component('empty', empty)
调用
toast =>>> this.$toast({ })
empty =>>> <empty></empty>
@components/toast/index.js
import vue from 'vue'
import toastComponent from './toast.vue'
const ToastConstructor = vue.extend(toastComponent)
function showToast ({text, duration = 2000, type = 'success', placement = 'top'}) {
const toastDom = new ToastConstructor({
el: document.createElement('div'),
data () {
return {
text: text,
show: true,
type,
placement
}
}
})
document.body.appendChild(toastDom.$el)
setTimeout(() => { toastDom.show = false }, duration)
}
// 注册为全局组件的函数
function registryToast() {
// 这样就可以在所有 vue 的实例里面使用 this.$toast()
vue.prototype.$toast = showToast
}
export default registryToast
@components/toast/toast.vue
<template>
<div class="toast"
:class="[placement]"
v-if="show"
>
<c-icon :type="type === 'success' ?'check-circle' : 'times-circle'"
size="18px"
:color="type ==='success'?'#4066f4': '#ff4f5f'"></c-icon>
<div class="title">{{text}}</div>
</div>
</template>
<script>
export default {
data () {
return {
placement: 'top',
text: '操作成功',
type: 'success'
}
}
}
</script>
<style scoped lang="scss">
.toast {
position: fixed;
left: 50%;
transform: translateX(-50%);
min- 240px;
background-color: #ffffff;
box-shadow: 0px 9px 11px 2px rgba(41, 42, 46, 0.18);
border-radius: 4px;
padding: 15px 20px;
display: flex;
align-items: center;
top: 0;
transition-duration: 0.8s;
&.top {
top: 84px;
}
.title {
font-size: 14px;
font-weight: bold;
color: #595959;
margin-left: 10px;
}
}
</style>
@components/empty/empty.vue
<template>
<div class="empty-history">
<img src="@/assets/images/empty1x.png"
alt="">
<div class="title">{{text}}</div>
</div>
</template>
<script>
export default {
data () {
return {
text: '暂无数据'
}
},
components: {
}
}
</script>
<style scoped lang="scss">
.empty-history {
text-align: center;
img {
margin-top: 5vh;
}
.title {
margin-top: 2vh;
font-size: 14px;
font-weight: 400;
line-height: 24px;
color: #4e5160;
}
}
</style>