本文共 3194 字,大约阅读时间需要 10 分钟。
1、展示一条提示消息,显示3s 中或者其他时间后消失
2、消息为自定义消息,展示多条消息,展示最新的消息 3、可关闭当前展示的消息首先在vue 项目中src 目录下,创建plugins目录,存放插件内容
── plugins │ │ └── ToastMessage │ │ ├── index.js │ │ └── index.vue承载组件的内容,在@/plugins/ToastMessage/index.vue文件里
我需要的内容不多,message 和show 来分别控制展示内容和展示与否{ {message}}
通常,将上面的组件直接引入到父组件,这为组件的使用,如果是插件,需要将改组件export 并extend在Vue 实例上。
将Vue 和上面的 组件引入进来import Vue from 'vue'import vueToastMessage from './index.vue'
将组件挂到Vue上,声明变量构造函数的变量、定时器的变量
let ToastTem = Vue.extend(vueToastMessage)let instancelet timer = null
生成构造函数,挂载到dom元素上,避免重复生成多个构造函数,需判断是否已经存在;
判断是否正在展示中,清空定时器,将展示的内容赋值为新内容; 通过定时器来控制展示的时长,如果未传参数,默认为3s;let toastMessage = (options) => { if (!instance) { instance = new ToastTem() instance.vm = instance.$mount() document.body.appendChild(instance.vm.$el) } console.log(options) if (timer) { clearTimeout(timer) timer = null instance.show = false instance.message = '' } let time = 3000 if (typeof options === 'string') { instance.message = options } else if (typeof options === 'object') { let { message, time} = options instance.message = message time = time || 3000 } else { return } instance.show = true timer = setTimeout(() => { instance.show = false clearTimeout(timer) timer = null instance.message = '' }, time)}
关闭toast
toastMessage.close = () => { if (timer) { clearTimeout(timer) timer = null instance.show = false instance.message = '' }}
以上直接在末尾export default toastMessage,即可在元素中调用,调用方法:
export default toastMessage
import toastMessage from '@/plugins/ToastMessage'toastMessage({ message: '123', time: 3000})
需要在export default toastMessageinstall,挂载到prototype
toastMessage.install = (Vue) => { Vue.prototype.$toastMessage = toastMessage}
在main.js 中引入
import toastMessage from '@/plugins/ToastMessage' // message 提示消息插件Vue.use(toastMessage)
this.$toastMessage({ message: '33333', time: 3000})
完整的@/plugins/ToastMessage/index.js 文件内容如下:
import Vue from 'vue'import vueToastMessage from './index.vue'let ToastTem = Vue.extend(vueToastMessage)let instancelet timer = nulllet toastMessage = (options) => { if (!instance) { instance = new ToastTem() instance.vm = instance.$mount() document.body.appendChild(instance.vm.$el) } console.log(options) if (timer) { clearTimeout(timer) timer = null instance.show = false instance.message = '' } let time = 3000 if (typeof options === 'string') { instance.message = options } else if (typeof options === 'object') { let { message, time} = options instance.message = message time = time || 3000 } else { return } instance.show = true timer = setTimeout(() => { instance.show = false clearTimeout(timer) timer = null instance.message = '' }, time)}toastMessage.close = () => { if (timer) { clearTimeout(timer) timer = null instance.show = false instance.message = '' }}toastMessage.install = (Vue) => { console.log('install--------toastMessage') Vue.prototype.$toastMessage = toastMessage}export default toastMessage
转载地址:http://xkhbb.baihongyu.com/