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

秒速五厘米 2022-11-28 10:43 293阅读 0赞

利用render(虚拟dom)

定义template组件 就是正常的组件 起名为index.vue

  1. <template>
  2. <transition name="fade" v-if="isShow">
  3. <!-- //success warn err default -->
  4. <div class="tip-box" :class="{ 'success':type =='success' ,'warn':type =='warn' ,'err':type =='err','default':type =='default'}" v-if="isShow">
  5. <div class="tip-box-content">
  6. {
  7. {content}}
  8. </div>
  9. </div>
  10. </transition>
  11. </template>
  12. <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>
  13. <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

  1. import Vue from "vue"
  2. import tipTemp from './index.vue'
  3. export default function tip1111(props) {
  4. const vm = new Vue({
  5. render(h) { //虚拟dom
  6. return h(tipTemp, { props }); //Component是要挂载的组件,props是要挂载组件的props属性
  7. }
  8. }).$mount();
  9. document.body.appendChild(vm.$el); //vm.$el是虚拟dom(vm)对应的真实dom,也可以用vm.$root替代vm.$el
  10. const comp = vm.$children[0]; //用与挂载全局的alert提示,comp就相当于alert组件。
  11. comp.remove = () => { //当执行remove()方法时,即从body上移除掉挂载的真实dom,并销毁虚拟dom
  12. document.body.removeChild(vm.$el);
  13. vm.$destroy(); //销毁虚拟dom
  14. }
  15. return comp
  16. }

在main.js中引入index.js 并挂载到根实例上

  1. import tip from "./components/tip/index.js"
  2. Vue.prototype.$tip = tip;

使用

  1. this.$tip({
  2. content: "提交成功!请等待工作人员与您联系。",
  3. type: "success"
  4. }).show();

发表评论

表情:
评论列表 (有 0 条评论,293人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Notice-Message消息提示

    常用于主动操作后的反馈提示。与 Notification 的区别是后者更多用于系统级通知的被动提醒。 当需要自定义更多属性时,Message 也可以接收一个对象为参数。比如,