Vue 封装动态组件

以前用js 封装过一个小的提示组件, 现在用vue再次封装下
查看效果地址 文章加载完, 就可以看到

Alert.vue




Alert.js

import alert from './Alert.vue'
let instance; 
const plugin = {
    install(vue) {
        let Alerting = vue.extend(alert);
        if(!instance){
            instance = new Alerting({
                el: document.createElement('div')
            })
            document.body.appendChild(instance.$el);
        }
        const alerting = {
            show (options = {}){
                if(typeof options === 'string'){
                    instance.message = options;
                    instance.flag = false;
                }
                else if(typeof options === 'object'){
                    instance.flag = options['flag'];
                    instance.message = options['text'];
                }
                instance.show();
            }
        }
        vue.$xalert = alerting;
        vue.mixin({
            created: function(){
                this.$xalert = vue.$xalert;
            }
        })
    }
}
export default plugin
export const install = plugin.install

在main.js 中全局引入

import loadding from './components/owner/ownerAlert/Alert.js'
Vue.use(loadding);

在其他页面想要使用

this.$xalert.show({
      text: "加载完成",
      flag: true
});

你可能感兴趣的:(Vue 封装动态组件)