<template> ?? ?<div > ?? ??? ?<div class="alert"> ? ? ? ? <div class="alert-main" v-for="item in notices" :key="item.name"> ? ? ? ? ? ? <div class="alert-content">{{ item.content }}</div> ? ? ? ? </div> ? ? </div> ?? ?</div > </template>
<script> ? ?//多个提示框命名 ? ? let seed = 0; ? ? function getuuid() { ? ? ? ? return 'alert_' + (seed++); ? ? } ?? ?export default { ?? ??? ?data() { ?? ??? ??? ?return { ? ? ? ? ? ? ? ? notices: []//多个提示框保存至数组 ?? ??? ??? ?} ?? ??? ?}, ?? ??? ?methods:{ ?? ??? ? ?add(notice) { ? ? ? ? ? ? ? ? const name = getuuid();//获取当前提示框名称 ? ? ? ? ? ? ? ? //object.assign 浅拷贝不会跳过那些值为 [null] 或 [undefined]的源对象 ? ? ? ? ? ? ? ? // object.assign(target, ...sources);target: 目标对象,sources:源对象 ? ? ? ? ? ? ? ? let _notice = object.assign({ ? ? ? ? ? ? ? ? ? ? name: name ? ? ? ? ? ? ? ? }, notice); ? ? ? ? ? ? ? ? //将当前提示框标签保存到notices ? ? ? ? ? ? ? ? this.notices.push(_notice); ? ? ? ? ? ? ? ? // 定时移除,单位:秒 ? ? ? ? ? ? ? ? const time= notice.time|| 1.5; ? ? ? ? ? ? ? ? //1.5s后调用移除方法 ? ? ? ? ? ? ? ? settimeout(() => { ? ? ? ? ? ? ? ? ? ? this.remove(name); ? ? ? ? ? ? ? ? }, time* 1000); ? ? ? ? ? ?}, ? ? ? ? ? remove(name) { ? ? ? ? ? ? ? ? const notices = this.notices; ? ? ? ? ? ? ? ? for (let i = 0; i < notices.length; i++) { ? ? ? ? ? ? ? ? ? ? if (notices[i].name === name) { ? ? ? ? ? ? ? ? ? ? ? ? this.notices.splice(i, 1); ? ? ? ? ? ? ? ? ? ? ? ? break; ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? ?} ?? ?} </script>
<style lang="scss"> </style>
import vue from 'vue' import alter from '/components/alter/alter.vue' //alter添加新属性,newinstance是个函数需求参数为properties alter.newinstance=properties=>{ ?? ?const props=properties || {}; ?? ?//创建一个vue组件对象 ?? ?const instance=new vue({ ?? ??? ?data:props, ?? ??? ?render(h){ ?? ??? ??? ?return h(alter,{ ?? ??? ??? ??? ?props:props ?? ??? ??? ?}) ?? ??? ?} ?? ?}); ?? ?//等待接口调用的时候在实例化组件,避免进入页面就直接挂载到body上 ?? ?const component=instance.$mount(); ?? ?//实例化一个组件,然后挂载到body上 ?? ?document.body.appendchild(component.$el); ?? ?//通过闭包维护alter组件的引用 ?? ?const alter=instance.$children[0]; ?? ?return{ ?? ??? ?//alter组件对外暴露的两个方法 ?? ??? ?add(noticeprops){ ?? ??? ??? ?alter.add(noticeprops); ?? ??? ?}, ?? ??? ?remove(name){ ?? ??? ??? ?alter.remove(name); ?? ??? ?} ?? ?} } //提示单例 let messageinstance; function getmessageinstance(){ ?? ?messageinstance=messageinstance || alter.newinstance(); ?? ?return messageinstance; } //定义函数实现 function notice({time='',content=''}){ ?? ?let instance=getmessageinstance(); ?? ?instance.add({ ?? ??? ?time:1.5, ?? ??? ?content:'' ?? ?}) } //公布方法 export default{ ?? ?info(options){ ?? ??? ?return notice(options); ?? ?} }
import alert from './alert.js' // 挂载到vue原型上 vue.prototype.$alert = alert // 然后在组件中使用 this.$alert.info({time: 1.5, content: '提示'})
在实际开发中一般有两种封装vue组件的方法:一种就是常用的的通过props父组件传值给子组件的方法:
还有一种就是通过调用api的形式,下面例子是本人在实际项目中封装的一个自定义图标的弹窗组件
首先实现组件的ui页面(css部分截图不完整)
在vue文件的同目录下新建alerttips.js文件
页面中调用方法:
以上为个人经验,希望能给大家一个参考,也希望大家多多支持本教程网。