vue 如何写出仿elementui的message消息提示 秒速五厘米 2022-11-28 10:43 211阅读 0赞 ## 利用render(虚拟dom) ## *定义template组件 就是正常的组件 起名为**index.vue*** <template> <transition name="fade" v-if="isShow"> <!-- //success warn err default --> <div class="tip-box" :class="{ 'success':type =='success' ,'warn':type =='warn' ,'err':type =='err','default':type =='default'}" v-if="isShow"> <div class="tip-box-content"> { {content}} </div> </div> </transition> </template> <script> export default { name: "tip", props:{ content:{ //消息内容 type:String, default:'', }, type:{ //显示类型 success warn err default type:String, default:'default',//success warn err default }, timer:{ //显示时间 type:Number, default:5000, } }, data() { return { isShow: false, }; }, methods: { show() { //组件显示方法 this.isShow = true; setTimeout(this.hide, this.timer); }, hide() { //组件隐藏方法 this.isShow = false; this.remove(); //当被挂载在create.js上是,this.remove()即执行comp.remove(),即从body上移除掉挂载的真实dom,并销毁虚拟dom } } }; </script> <style lang="scss" scoped> .tip-box { position: fixed; left: 35%; top: 10px; font-size: 14px; width: 30%; padding: 20px 0; border-radius: 10px; letter-spacing: 1px; text-align: center; z-index: 9999; color: #fff; .tip-box-content{ width: 90%; margin: 0 auto; } } .fade-enter-active, .fade-leave-active { transition: opacity 0.2s; } .fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ { opacity: 0; } .success{ background: #67C23A; } .warn{ background: #E6A23C; } .err{ background: #e24747; } .default{ background: #909399; } </style> *用template组件创建虚拟dom 起名为 **index.js*** import Vue from "vue" import tipTemp from './index.vue' export default function tip1111(props) { const vm = new Vue({ render(h) { //虚拟dom return h(tipTemp, { props }); //Component是要挂载的组件,props是要挂载组件的props属性 } }).$mount(); document.body.appendChild(vm.$el); //vm.$el是虚拟dom(vm)对应的真实dom,也可以用vm.$root替代vm.$el const comp = vm.$children[0]; //用与挂载全局的alert提示,comp就相当于alert组件。 comp.remove = () => { //当执行remove()方法时,即从body上移除掉挂载的真实dom,并销毁虚拟dom document.body.removeChild(vm.$el); vm.$destroy(); //销毁虚拟dom } return comp } 在main.js中引入index.js 并挂载到根实例上 import tip from "./components/tip/index.js" Vue.prototype.$tip = tip; *使用* this.$tip({ content: "提交成功!请等待工作人员与您联系。", type: "success" }).show();
还没有评论,来说两句吧...