function registryToast() {
// 将组件注册到 vue 的 原型链里去,
// 这样就可以在所有 vue 的实例里面使用 this.$toast()
vue.prototype.$toast = showToast
}
export default registryToast
附一个传送门vue.extend 官方文档
四. 试用
到这里,我们已经初步完成了一个可以全局注册和动态加载的toast组件,接下来我们来试用一下看看
在vue的入口文件(脚手架生成的话是 ./src/main.js ) 注册一下组件
文件位置 /src/main.js
import toastRegistry from './toast/index'// 这里也可以直接执行 toastRegistry()
Vue.use(toastRegistry)
我们稍微修改一下使用方式,把 第二步 的引用静态组件的代码,改成如下
<template>
<div id="app">
<input type="button" value="显示弹窗" @click="showToast">
</div>
</template>
<script>
export default {
methods: {
showToast () {
this.$toast('我是弹出消息')
}
}
}
</script>
可以看到,我们已经 不需要 在页面里面 引入 跟 注册 组件,就可以直接使用 this.$toast() 了.
五. 优化
现在我们已经初步实现了一个弹窗.不过离成功还差一点点,缺少一个动画,现在的弹出和隐藏都很生硬.
我们再对 toast/index.js 里的 showToast 函数稍微做一下修改(有注释的地方是有改动的)
文件位置 /src/toast/index.js
function showToast(text, duration = 2000) {
const toastDom = new ToastConstructor({
el: document.createElement('div'),
data() {
return {
text:text,
showWrap:true, // 是否显示组件
showContent:true // 作用:在隐藏组件之前,显示隐藏动画
}
}
})
document.body.appendChild(toastDom.$el) // 提前 250ms 执行淡出动画(因为我们再css里面设置的隐藏动画持续是250ms)
setTimeout(() => {toastDom.showContent = false} ,duration - 1250)
// 过了 duration 时间后隐藏整个组件
setTimeout(() => {toastDom.showWrap = false} ,duration)
}
然后,再修改一下toast.vue的样式
文件位置 /src/toast/toast.vue
<template>
<div class="wrap" v-if="showWrap" :class="showContent ?'fadein':'fadeout'">{{text}}</div>
</template><style scoped>
.wrap{
position: fixed;
left: 50%;
top:50%;
background: rgba(0,0,0,.35);
padding: 10px;
border-radius: 5px;
transform: translate(-50%,-50%);
color:#fff;
}
.fadein {
animation: animate_in 0.25s;
}
.fadeout {
animation: animate_out 0.25s;










