vue 如何写出仿elementui的message消息提示

利用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();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值