1、效果圖css
2、說明vue
這類提示框組件咱們一般都會直接在 JS 代碼中進行調用。像下面這樣:app
this.$toast('別點啦,到頭啦!')
但看到網上大多數仍是經過 component 方式實現的,這樣的話咱們在使用的時候還要在 DOM 中放置一個組件元素,而後經過一個變量來控制它的顯示隱藏,這樣使用起來很是的不方便。那麼有什麼方法能夠不用在 DOM 中手動放置組件元素就能夠直接調用呢?答案就是 Vue.extend。經過 Vue.extend 方式實現的組件,須要兩個文件,一個是 .vue 文件,另一個就是管理 .vue 的 .js 文件。具體代碼以下:dom
3、代碼函數
Toast.vue 文件代碼this
<template> <div class="toast" v-show="visible"> {{ message }} </div> </template> <script> export default { name: 'toast', data () { return { message: '', // 消息文字 duration: 3000, // 顯示時長,毫秒 closed: false, // 用來判斷消息框是否關閉 timer: null, // 計時器 visible: false // 是否顯示 } }, mounted () { this.startTimer() }, watch: { closed (newVal) { if (newVal) { this.visible = false this.destroyElement() } } }, methods: { destroyElement () { this.$destroy() this.$el.parentNode.removeChild(this.$el) }, startTimer () { this.timer = setTimeout(() => { if (!this.closed) { this.closed = true clearTimeout(this.timer) } }, this.duration) } } } </script> <style lang="scss" scoped> .toast { position: fixed; bottom: 15vh; left: 28vw; min-width: 40vw; max-width: 100vw; font-size: 26px; text-align: center; padding: 10px 2vw; border-radius: 40px; background-color: rgba(0, 0, 0 , 0.6); color: rgb(223, 219, 219); letter-spacing: 3px; } </style>
Toast.js 文件代碼spa
import Vue from 'vue' import Toast from '@/components/layer/Toast.vue' let ToastConstructor = Vue.extend(Toast) // 構造函數 let instance // 實例對象 let seed = 1 // 計數 const ToastDialog = (options = {}) => { if (typeof options === 'string') { options = { message: options } } let id = `toast_${seed++}` instance = new ToastConstructor({ data: options }) instance.id = id instance.vm = instance.$mount() document.body.appendChild(instance.vm.$el) instance.vm.visible = true instance.dom = instance.vm.$el instance.dom.style.zIndex = 999 + seed return instance.vm } export default ToastDialog
4、使用code
首先在 main.js 中引入 Toast.js 並掛載到vue原型上,以下圖:component
其次,在代碼中使用對象
this.$toast('別點啦,到頭啦!')