Skip to main content

Command Palette

Search for a command to run...

vue2实现`this.$notice`,页面弹窗提示

Published
1 min readView as Markdown

效果

代码

// main.js
Vue.prototype.$notice = (arg) => {
  createwomo(Noticewomo, arg)
}
// createwomo.js
import Vue from 'vue'
// export const createwomo = function(component, arg) {
export function createwomo (component, props) {
  // vue实例对象
  const vm = new Vue({
    render: (h) => {
      // 必须用props作为形参,{ props },一个对象,对象里有 props 属性。 props 属性本身是一个对象。
      return h(component, { props })
    }
  })
  // 调用挂载方法,可以原生dom节点
  vm.$mount()
  // vm.$el 是一个原生dom节点对象
  document.body.appendChild(vm.$el)  
  // vue组件对象
  const comp = vm.$children[0]
  comp.remove = () => {
    document.body.removeChild(vm.$el)
    // 消除 watcher、listener、实例、vue引用等等
    vm.$destroy()
  }
}
<!-- Noticewomo.vue -->
<template>
<div class="box" v-if="isShow">
  <h3>{{ title }}</h3>
  <p class="box-content">{{ message }}</p>
</div>
</template>
<script>
export default {
  data(){
    return {
      isShow: false
    }
  },
  props: {
    title: {
      type: String,
      default: ''
    },
    message: {
      type: String,
      default: ''
    },
    duration: {
      type: Number,
      default: 1000,
    }
  },
  mounted(){
    this.show()    
  },
  methods: {
    show() {
      this.isShow = true
      setTimeout(this.hide, this.duration)
    },
    hide() {
      this.isShow = false
      this.remove()
    }
  }
}
</script>
<style>
.box {
  position: fixed;
  width: 40%;
  top: 10px;
  left: 50%;
  transform: translate(-50%);
  text-align: center;
  pointer-events: none;
  border-color: #fff;
  border: gray 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>

More from this blog

EddieQiao's blog

84 posts

coder, work in suzhou