vue-extend和vue-component註冊一個全局組件

extend()是一個全局構造器,生成的是一個還沒掛載到頁面元素上的組件實例。

在全局掛載插件的形式全局註冊,就需要用到vue.use()方法,官方文檔:

所以插件必須是一個對象,並且提供install方法,註冊的時候自動調用該方法。

所以組件的寫作步驟就清晰了一些了,實踐出真知,現在就來練習一下寫一個簡約版的全局alert彈框

1、在components文件夾下新建alert文件夾,裏面首先新建一個alert.vue文件

<!-- alert -->
<template>
    <div class="alert" v-show="showAlert">
        <p class="msg">{{ msg }}</p>
    </div>
</template>

<script>
export default {
    props: {
        msg: {
            type: String,
            default: ''
        },
        showAlert: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {};
    },
    //方法集合
    methods: {}
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css類
.alert {
    position: fixed;
    left: 50%;
    transform: translateX(-50%);
    .msg {
        text-align: center;
        font-size: 20px;
        padding: 5px 10px;
    }
}
</style>

2、然後在alert文件下再新建一個alert.js文件,寫擴展插件的js

import Alert from "./alert.vue";
const ALERT = {
    install(Vue) {
        Vue.component('alert', Alert); // 一定先註冊

        Vue.prototype.$alert = (text) => {
            let VueAlert = Vue.extend({
                data() {
                    return {
                        msg: '',
                        showAlert: false
                    }
                },
                render(h) {
                    let props = {
                        msg: this.msg,
                        showAlert: this.showAlert,
                    }
                    return h('alert', {
                        props
                    })
                }
            });
            let newAlert = new VueAlert();
            let vm = newAlert.$mount();
            let el = vm.$el;
            document.body.appendChild(el); // 添加到頁面中
            vm.showAlert = true;
            vm.msg = text;
        }
    }
}
export default ALERT;

3、在main.js中引入

、、、、
import diyAlert from '@/components/alert/alert'; // extentd寫alert
、、、
Vue.use(diyAlert);

4、這樣就可以在全局調用了:

<!-- extend寫message -->
<template>
    <div class="extentd">
         <el-button type="primary" @click="alert">alert</el-button>
    </div>
</template>

<script>
export default {
    data() {
        return {};
    },
    //方法集合
    methods: {
        alert() {
            this.$alert('hahahah');
        }
    }
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css類
</style>

剩下的就是在此基礎上進行功能性擴展了,比如關閉,動效等,就簡單了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章