在项目中经常遇到提示信息组件,我们·一般会用ui库来做。但是当ui库无法满足自己的需求(比如自定样式,ui库的样式很难改变)。下面就是简单封装一个自己的Alert信息提示框。
1.我们要做得是alert组件所以要预设几个字段
title -标题message -提示信息duration -显示时间2.给出创建组件的方法
3.挂载到全局vue实例
4.调用
1.创建一个ui组件(Alert)
<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 //默认1000毫秒消失 } }, data() { return { isShow: false //是否显示标识 }; }, methods: { show() { this.isShow = true; setTimeout(this.hide, this.duration);//设置时间自动消失 }, hide() { this.isShow = false; this.remove();//移除 } } }; </script> <style> .box { position: fixed; width: 100%; top: 16px; left: 0; text-align: center; pointer-events: none; background-color: #fff; border: grey 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>2.写一个创建Alert的函数(新建一个create.js)
import Vue from 'vue' // 传入一个组件配置 // 创建它的实例,并且将它挂载到body上 // 返回组件实例 export default function create(Component, props) {//Component组件 props传进来的参数 //方式一:使用Vue.extend创建 const Ctor = Vue.extend(Component); //创建组件实例 const comp = new Ctor({ propsData: props }) //挂载 comp.$mount(); document.body.appendChild(comp.$el);//把元素追加到body后面 //移除 comp.remove = () => { document.body.removeChild(comp.$el) //移除元素 comp.$destroy() //销毁 } // // 方式二:new一个Vue // const vm = new Vue({ // render(h) { // return h(Component, { props }) // } // }).$mount() // $mount()本质上将vdom=》dom // // 通过vm.$el获取生成的dom // document.body.appendChild(vm.$el) // // 删除函数 // // 获取组件实例 // const comp = vm.$children[0] // comp.remove = () => { // document.body.removeChild(vm.$el) // vm.$destroy() // } return comp }3.挂载到全局vue实例中(方便调用)
1.在main.js 里引入create文件和Alert组件
2.挂载到vue的原型上
代码如下:
import Vue from 'vue' import App from './App.vue' import './plugins/element.js' import Create from './utils/create.js'; import Alert from './components/Alert.vue'; Vue.config.productionTip = false Vue.prototype.$Alert= ((obj)=>{//挂载在原型上 return Create(Alert,obj).show(); //返回组件实例 }) new Vue({ render: h => h(App), }).$mount('#app')4.使用方式
this.$Alert({message:"5555",title:"测试",duration:3000});
如果不懂Vue.extends()/$mounted()/$destory可以看一下vue官方API---vue官方API文档传送门
这个只是一个简单的组件,我只是给出了一个自定义组件的方法,可以自己往里面加样式,其他字段都行