文中默認對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