比如我们有一个要求就是:实现一个类似于element ui 的 Toast 单框,而element ui 的 Toast 弹框又不能满足我们现阶段的需求,那么就可以使用Vue.extend + $mountl来实现。
如下图
如上图所示
建立一个Toast.vue 在这个里面写你想要的Toast 弹框样式
<template> <div class="CustToast" :class="type" v-if="showToast"> <span class="icon"> <img :src="iconSrc" /> </span> {{ message }} </div> </template> <script> export default { /** * 自己封装的Toast v0.2 * params: showToast Boolean 是否激活toast 默认 false * params: type String toast提示类型 共normal success,fail,warning 四个选项 默认normal * params: message String toast消息 * params: duration Number toast显示时间 默认 3000ms * */ name: 'CustToast', data () { return { showToast: true, type: 'normal', message: '消息提示', duration: 3000 } }, computed: { iconSrc () { window.console.log('当前类型', this.type) const tipType = ['normal', 'success', 'warning', 'fail'] if (tipType.includes(this.type)) { return require(`@/assets/img/common/${this.type}.svg`) } else { // eslint-disable-next-line no-throw-literal throw 'Toast type数据只允许为 normal, success, warning, fail 四种其中的一种,默认为normal' } } } } </script> <style scoped> .CustToast { position: fixed; left: 50%; top: 50%; background: rgb(233, 233, 235); padding: 10px; border-radius: 5px; transform: translate(-50%, -50%); animation: show-toast 0.2s; color: #909399; 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); } .icon img { width: 20px; height: 20px; margin-top: 3px; margin-right: 4px; } </style>
新建一个index.js文件
在点js 文件中写一下代码
import vue from 'vue' // 导入自定义到Toast组件 import CustToast from './CustToast.vue' // 生成一个扩展实例构造器 const ToastConstructor = vue.extend(CustToast) // 定义弹出组件的函数 接收三个参数 消息 toast类型 显示时间 function showToast (message, type = 'normal', duration = 2000) { // 实例化一个 CustToast.vue const _toast = new ToastConstructor({ data () { return { showToast: true, type: type, message: message, duration: duration } } }) // 把实例化的 CustToast.vue 添加到 body 里 const element = _toast.$mount().$el document.body.appendChild(element) // duration时间到了后隐藏 setTimeout(() => { _toast.showToast = false }, duration) } // 需要在main.js 里面使用 Vue.use(showToast); showToast.install = (Vue) => { // 将组件注册到 vue 的 原型链里去, // 这样就可以在所有 vue 的实例里面使用 this.$toast() Vue.prototype.$toast = showToast } // 导出 export default showToast
在你的vue项目的 main.js 中导入就可以全局使用了
使用
使用效果
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。