Notice組件實現

組件實例建立函數:create函數

import Vue from 'vue'
export default function create (Component, props) {
    // 先建立實例
    const vm = new Vue({
        render (h) {
       //h就是createElement,它返回VNode
          return h(Component, {props})
        }
    }).$mount()
    // 手動掛載
    document.body.appendChild(vm.$el)
    //銷燬方法
    const comp = vm.$children[0]
    comp.remove = function() {
      document.body.removeChild(vm.$el)
      vm.$destroy()
    }
    return comp
}

Notice組件

// 插槽預留
// 標題。內容等屬性
// 自動關閉
<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>

使用

<script>
import Notice from '@/components/notice/Notice'
export default {
  methods: {
    submitForm(form) {
      this.$refs[form].validate(valid => {
        const notice = this.$create(Notice,{
          title:'jdfksjf',
          message: valid ? "請求登陸!" : "校驗失敗",
          duration:1000
        })
        notice.show()
      })
    }
  }
}
</script>
相關文章
相關標籤/搜索