Vue 用extend实现alert效果 最简单直接版本 包懂

Vue 用extend实现alert效果 最简单直接版本 包懂

组件


<template>
  <div class="box"
       v-if="isShow">
    <h3>{{title}}</h3>
    <p class="box-content">{{message}}</p>
  </div>
</template>

<script>
export default {
  props: {
    title: {
      type: String,
      default: ""
    },
    message: {
      type: String,
      default: ""
    },
    duration: {
      type: Number,
      default: 2000
    }
  },
  data() {
    return {
      isShow: false
    };

  },
  methods: {
    show() {
      this.isShow = true;
      setTimeout(this.hide, this.duration);
    },
    hide() {
      this.isShow = false;
      this.remove();
    }
  }
};
</script>

<style>
.box {
  position: fixed;
  width: 100%;
  top: 16px;
  left: 0;
  text-align: center;
  pointer-events: none;
  background-color: #fff;
  border: grey 3px solid;
  box-sizing: border-box;
}
.box-content {
  width: 200px;
  margin: 10px auto;
  font-size: 14px;
  padding: 8px 16px;
  background: #fff;
  border-radius: 3px;
  margin-bottom: 8px;
}
</style>

动态生成并绑定Vue的prototype

import Vue from 'vue';
import alert from '@/components/Notice2'

let MyAlertConstructor = Vue.extend(alert);


let instance;
const MyAlert = (option) => {
  // 创建实例并且过滤参数
  instance = new MyAlertConstructor({
    propsData: {
      ...option
    }
  })

  // 挂载实例
  instance.$mount();
  instance.remove = () => {
    // 删除dom
    document.body.removeChild(instance.$el)

    // 销毁组件
    instance.$destroy()
  }
  console.log('alert', alert, ', MyAlertConstructor', MyAlertConstructor, 'option', option, 'instance', instance, 'instance.$el', instance.$el);

  document.body.appendChild(instance.$el);
  return instance;
}
// 挂载到Vue原型上
Vue.prototype.$alert = (opts) => {
  const comp = MyAlert(opts)
  comp.show()
  return comp
};

1用extend创建一个子类组件 2用子类组件new出一个vue实例,额外的参数用propsData传入 3把创建的实例用el就能访问到真是dom,用document.body.append把真实dom添加到body下 5.给组件注册remove事件,也就是remove事件的时候移除body下之前添加的dom 然后销毁vue实例

调用

      this.$alert({
          title: '校验完成',
          message: '校验失败,请重试!'
        })

本文使用 mdnice 排版

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值