文中默认对vue/cli已经理解。 写该文章是版本为4.xcss
在components文件中 新建一个notice文件夹 cd notice
新建一个Notice.vuevue
<template> <div class="notice" v-if="isShow"> <h4>{{title}}</h4> <p>{{content}}</p> </div> </template> <script> export default { name: 'Notice', props: { title: { type: String, default: '' }, content: { type: String, default: '' }, duration: { type: Number, default: 2000 // 默认2秒后消失 } }, data () { return { isShow: false, } }, methods: { hide() { this.isShow = false; this.remove(); // 组件销毁 } }, mounted () { this.isShow = true; setTimeout( this.hide,this.duration) } } </script> <style lang="scss" scoped> .notice { width: 200px; border: 1px solid #333; padding: 10px; position: absolute; right: 0; } </style>
新建一个index.js文件 主要是组件实例的建立功能app
import Vue from 'vue' import Notice from './Notice.vue' const NoticeController = Vue.extend(Notice) function notice(options) { const nc = new NoticeController({ propsData: options // propsData 用于值得传递 }); nc.$mount(); // 挂载 document.body.appendChild(nc.$el); // 插入body当中 nc.remove = function () { // 该方法用于销毁实例 document.body.removeChild(nc.$el); nc.$destroy() } console.log(nc); return nc; } export default notice
主要功能基本都实现
选择就是用于页面的实现的效果了ide
第一步 把组件实例注册全局中 main.jsui
import notice from './components/notice/index' Vue.prototype.$notice = notice
第二步,建立一个用于实现弹窗的按钮 组件 XButton.vuethis
<template> <div> <button @click="click">通知信息按钮</button> </div> </template> <script> export default { methods: { click() { this.$emit('click') } }, } </script>
第三步,把这个按钮组件挂载某个页面上 好比说: home.vueprototype
<template> <div class="home"> <x-button @click="open"></x-button> </div> </template> <script> // @ is an alias to /src import XButton from '@/components/XButton.vue' export default { name: 'Home', components: { XButton }, methods: { open() { this.$notice({ title: 'xuwen', content: '123' }) } }, } </script>
整一个弹窗的组件完成了,该弹窗组件是以element ui 中的弹窗组件 为原型实现的code