Vue之简易弹窗组件

tech2022-07-16  178

组件模板 Notice.vue

<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> <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>

创建组件实例 create.js

import Vue from "vue"; // 传递一个组件配置,返回一个组件实例,并且挂载它到body上 function create(Component, props) { // 组件实例创建 const Ctor = Vue.extend(Component); const comp = new Ctor({propsData: props}) comp.$mount() // dom追加 document.body.appendChild(comp.$el) // 获取组件实例 comp.remove = () => { document.body.removeChild(comp.$el) comp.$destroy() } return comp } export default create;

编写插件,挂载到vue原型上,便于全局调用 notice.js

import Notice from "../components/Notice.vue" import create from "../utils/create" export default { install(Vue){ Vue.prototype.$notice = function(options){ create(Notice,options).show(); } } }

main.js引入使用

import notice from './plugins/notice.js' Vue.use(notice)

组件内调用

this.$notice({ title: "请求成功", message: "成功", duration: 3000, })

效果展示

最新回复(0)