制作一个在body下的弹窗

1. 弹窗的组件,Notice.vue

    代码显示 

    //  Notice.vue 

<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: 1000
    }
  },
  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>

2. 弹窗的js,create.js

    代码显示 

    // 方法一:使用new Vue()的形式生成一个实例,然后挂载

import Vue from 'vue'
export default function create(Component, props) {
// 方法一: 使用 new Vue 生成
  const vm = new Vue({
    render(h) {
      return h(Component, {props})
    }
  }).$mount()

  document.body.appendChild(vm.$el)
  const comp = vm.$children[0];
  comp.remove = () => {
    document.body.removeChild(vm.$el)
    vm.$destroy()
  }
  return comp
}

这里 用了h函数:render(h){return h(Component, {props})}

用JSX实现:

render() {
      return (
        <Component 
          title = {props.title}
          message = {props.message}
          duration = {props.duration}
        >< /Component>
      )
 }

// 方法二:用Vue.extend()创建一个“子类”,参数是一个包含组件选项的对象,通过propsData传参。

import Vue from 'vue'
export default function create(Component, props) {
// 方法二: 使用 Vue.extend()
  const Ctor = Vue.extend(Component)
  const comp = new Ctor({
    propsData: props
  }).$mount()
  document.body.appendChild(comp.$el)
  comp.remove = () => {
    document.body.removeChild(comp.$el)
    comp.$destroy()
  }
  return comp
}

3.在想要展示的页面组件里引用create.js与Notice.vue

 

    import create from "@/utils/create";

    import Notice from "@/components/Notice";

 

   让弹窗显示的js

const notice = create(Notice, {
  title: "这是一个弹窗",
  message: "这是一个弹窗!",
  duration: 1000
});

notice.show();

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值